If you don't want to write a class for mirroring the entire JSON structure you could use SimpleJSON (copy paste the SimpleJSON.cs
into your Assets) and do something like
IEnumerator Start()
{
UnityWebRequest wr = UnityWebRequest.Get("http://localhost:55150/api/values");
yield return wr.SendWebRequest();
string a = wr.downloadHandler.text;
Debug.Log(a);
var jsonObject = JSON.Parse(a);
foreach (var element in jsonObject)
{
var elementName = element.Value["name"];
// do something with elementName
Debug.Log(elementName);
}
}
Update: sorting
Since you requested also sorting: You can do that using Linq OrderBy and OrderByDescending. Luckily SimpleJSON
already has an implementation for that so you can use .Linq
to make jsonObject
an IEnumerable
:
using System.Linq;
//...
var jsonObject = JSON.Parse(a);
foreach (var element in jsonObject.Linq.OrderByDescending(kvp => int.Parse(kvp.Value["id"])))
{
var elementName = element.Value["name"];
// do something with elementName
Debug.Log(elementName);
}
Note that this might throw exceptions for any wrong formatted JSON string.
Otherwise you have to implement the whole structure as class (and a wrapper since you get a List) and can use Unity JsonUtility
[Serializable]
public class DataList
{
public List<DataItem> items = new List<DataItem>();
}
[Serializable]
public class DataItem
{
public int id;
public string name;
public string family;
public string des;
}
and do
IEnumerator Start()
{
UnityWebRequest wr = UnityWebRequest.Get("http://localhost:55150/api/values");
yield return wr.SendWebRequest();
string a = wr.downloadHandler.text;
Debug.Log(a);
DataList dataList = JsonUtility.FromJson<DataList>(a);
foreach (DataItem item in dataList.items)
{
// do something with element.name
Debug.Log(item.name);
}
}