- Home /
How to get values from nested JSON data with foreach or for loop?
Hi, I have got the json data, its really long and has a lot of nested data which i need. If the json looks like this :
result
[{
"description":"eyes",
"measurement_locations":
[{
"AOI_radius_o":81.73,
"AOI_x_o":445.06740399339611,
"AOI_y_o":1147.187748624817,
"description":"left eye",
"measures":
[
{
"description":"eyebags",
"value":0.095144319232841418,
"value_raw":null
},
{
"description":"dark circles",
"value":0.18982207370058865,
"value_raw":null
}
],
"value":0.18982207370058865,
"value_raw":null,
"visualization_data":null
},
{
"AOI_radius_o":81.73,
"AOI_x_o":720.56740399339606,
"AOI_y_o":1127.6877486248172,
"description":"right eye"
,"measures":
[
{
"description":"eyebags",
"value":0.092195747704466202,
"value_raw":null
},
{
"description":"dark circles",
"value":0.23332688013566055,
"value_raw":null}],
"value":0.23332688013566055,
"value_raw":null,"visualization_data":null
}],
"message":"Ok",
"value":0.21157447691812459,
"value_raw":null
}]
i can get the description, and value but I'm not sure how to get the nested data like measurement_locations. How i get the "top level" data is by for loop like :
public List<string> description;
public List<float> value;
public void ReceiveResults(string jsonstring)
{
Debug.Log("ReceiveResults function");
ApiResponse response = JsonUtility.FromJson<ApiResponse>(jsonstring);
for (int i = 0; i < response.results.Count; i++)
{
description.Add(response.results[i].description);
value.Add(response.results[i].value);
}
}
public class ApiResponse
{
public List<SkinResult> results;
}
[System.Serializable]
public class SkinResult
{
public string description;
//Not sure what to do with this
public List<Measurement_Location> measurement_locations;
public float value;
}
[System.Serializable]
public class Measurement_Location
{
public float AOI_x_o;
public float AOI_y_o;
public string description;
}
Comment
Answer by ndmrzk · Feb 11, 2020 at 08:39 AM
So we ended up making the ApiResponse class Serializable. Then using foreach to get the values we wanted depending on the dot notation
foreach(var location in response.results[3].measurement_locations)
{
foreach (var data in location.visualization_data)
{
List<float> data_x = new List<float>();
List<float> data_y = new List<float>();
int index = 0;
foreach (var point_x in data.x)
{
data_x.Add(point_x);
}
foreach (var point_y in data.y)
{
data_y.Add(point_y);
Debug.Log("data_x = " + data_x[index] + "and data_y is " + data_y[index]);
index++;
}
}
}
Your answer
Follow this Question
Related Questions
my wave spawner not working properly 1 Answer
Which is a faster find? (foreach) or (for-loop) 2 Answers
For loop update variables value before functions complete 2 Answers
JSON Loading of Position 0 Answers