所以今天我被困在試圖圍繞 JSON 以及圍繞它的所有魔力,
我有兩個腳本:
JsonDataClass(用于定義類)
[Serializable]
public class JsonDataClass
{
public List<DataList> data;
public int code;
}
[Serializable]
public class DataList
{
public string priceCOIN;
public string currency;
}
JsonController(用于獲取資訊)
public class JsonController : MonoBehaviour
{
public string jsonURL = "https://www.enter.art/api/FetchNFTPricing?walletAddress=0xCA3B0f72ae4fB4841F669614Ffc421c0ED68b943&tokenId=35237";
public void Start()
{
StartCoroutine(GetData());
}
IEnumerator GetData()
{
Debug.Log("Processing Data...");
WWW _www = new WWW(jsonURL);
yield return _www;
if (_www.error == null)
{
processJsonData(_www.text);
}
else
{
Debug.Log("Oops, we were unable to retrieve the data");
}
}
public void processJsonData(string _url)
{
JsonDataClass jsnData = JsonUtility.FromJson<JsonDataClass>(_url);
Debug.Log(jsnData.code);
foreach (DataList x in jsnData.data)
{
Debug.Log(x.currency);
}
}
}
在JsonController腳本中jsnData.code記錄為200.
但是,似乎我無法序列化資料串列,因為它永遠不會被記錄?
我想認為我的課程是正確的,并且一切都應該正常作業,但事實并非如此。
對此的任何幫助將不勝感激。準備從窗戶扔出去。
uj5u.com熱心網友回復:
JsonUtility不支持嵌套 json。所以,修改你的類屬性,如果你擺脫了嵌套的 json 并且你的整個 json 看起來像這樣,它應該可以作業(使用正確的引號等):
data: {
priceCOIN: "37 Bn",
priceUSD: "10.52",
priceBigInt: "37265358313000000000",
currency: "NFTART",
supply: 1,
type: "listing"
}
一般來說,Unity 不需要重新決議 JSON 會更方便。使用更完整的 JSON 解決方案:使用NewtonsoftUnity 內置包管理器https://docs.unity3d.com/Packages/[email protected]/manual/index.html
uj5u.com熱心網友回復:
你在你的 json 中得到了什么
{
"code": 200,
"data": {
"priceCOIN": "37 Bn",
"priceUSD": "10.47",
"priceBigInt": "37265358313000000000",
"currency": "NFTART",
"supply": 1,
"type": "listing"
}
}
不是串列。它只是一個簡單的嵌套物件,因此您的資料結構應該看起來像
[Serializable]
public class Root
{
public Data data;
public int code;
}
[Serializable]
public class Data
{
public string priceCOIN;
public string currency;
}
然后
public void processJsonData(string data)
{
var jsnData = JsonUtility.FromJson<Root>(data);
Debug.Log(jsnData.code);
Debug.Log(jsnData.data.currency);
}
應該按預期作業。
一般來說WWW,現在已經過時了一段時間,你應該使用UnityWebrequest.Get
IEnumerator GetData()
{
Debug.Log("Processing Data...");
using (var www = UnityWebRequest.Get(jsonURL))
{
yield return www.SendWebRequest();
if(www.result == UnityWebRequest.Result.Success)
{
processJsonData(www.downloadHandler.text);
}
else
{
Debug.Log("Oops, we were unable to retrieve the data");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432338.html
