我有一个在线生成的随机JSON,并且能够打印所有值。但是,如何分别读取每个数组?例如,下面的JSON包含不同的属性,我如何读取字符串name
,它是一个包含4个值的数组。
JSON阅读器:
public class JsonHelper
{
public static T[] getJsonArray<T>(string json)
{
string newJson = "{ \"array\": " + json + "}";
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
return wrapper.array;
}
[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
}
[System.Serializable]
public class RootObject
{
public string name;
public string height;
public string mass ;
}
以下脚本用于通过RESTApi GET服务在线访问JSON。我能够接收全部文本,但是如何读取name
或height
或mass
的单个值?
脚本:
using UnityEngine.Networking;
using System.Linq;
using System.Linq.Expressions;
using UnityEngine.UI;
using System.IO;
public class GetData : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(GetNames());
}
IEnumerator GetNames()
{
string GetNameURL = "https://swapi.co/api/people/1/?format=json";
using(UnityWebRequest www = UnityWebRequest.Get(GetNameURL))
{
// www.chunkedTransfer = false;
yield return www.Send();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
if(www.isDone)
{
string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(jsonResult); //I am getting the result here
}
}
}
}
}
答案 0 :(得分:2)
您对“ https://swapi.co/api/people/1/?format=json”的API调用返回一个对象,而不是一个数组。
因此,在获取json后,您可以访问名称和高度,例如:
if (www.isDone)
{
string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(jsonResult); //I am getting the result here
RootObject person = JsonUtility.FromJson<RootObject>(jsonResult);
// then you can access each property
Debug.Log(person.name);
Debug.Log(person.height);
}