我正在统一获取Web api,但出现错误。 这是错误。
ArgumentException:JSON必须表示一个对象类型。 UnityEngine.JsonUtility.FromJson(System.String json,System.Type 类型)(在 C:/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:42) UnityEngine.JsonUtility.FromJson [T](System.String json)(在 C:/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:30) RestClient + d__3.MoveNext()(位于Assets / _Scripts / RestClient.cs:34) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator枚举器,System.IntPtr returnValueAddress)(在 C:/buildslave/unity/build/Runtime/Export/Scripting/Coroutines.cs:17)
这是我的json响应
[
{
"id":"1",
"name":"Yasir",
"mobile":"0301",
"password":"123"
},
{
"id":"2",
"name":"Mehmood",
"mobile":"0302",
"password":"123"
},
{
"id":"3",
"name":"Imran",
"mobile":"0301",
"password":"123"
},
{
"id":"4",
"name":"Iqbal",
"mobile":"0302",
"password":"123"
}
]
ReastClient.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class RestClient : MonoBehaviour
{
private static RestClient _instance;
public static RestClient Instance{
get{
if(_instance == null){
_instance = FindObjectOfType<RestClient>();
if(_instance == null){
GameObject go = new GameObject();
go.name =typeof(RestClient).Name;
_instance = go.AddComponent<RestClient>();
}
}
return _instance;
}
}
public IEnumerator Get(string url, System.Action<PlayerList> callBack)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.SendWebRequest();
if (www.isNetworkError)
{
print(www.error);
}else if (www.isDone)
{
string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
PlayerList playerlist = JsonUtility.FromJson<PlayerList>(jsonResult);
callBack(playerlist);
}
}
}
}
Game.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game : MonoBehaviour
{
public string web_url = "";
// Start is called before the first frame update
void Start()
{
StartCoroutine(RestClient.Instance.Get(web_url,GetPlayers));
}
void GetPlayers(PlayerList playerlist)
{
foreach(Player player in PlayerList.players)
{
print("Player Id = " + player.id);
}
}
}
PlayerList.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerList
{
public static List<Player> players;
}
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Player
{
public int id;
public string name;
public string mobile;
public string password;
}
答案 0 :(得分:1)
我猜想JsonUtility.FromJson<T>
期望一个对象不只是“数组”。
所以json应该看起来像这样:
{
"players": [
{
"id":"1",
"name":"Yasir",
"mobile":"0301",
"password":"123"
},
...
]
}
,然后PlayerList
的字段players
不能是静态的。