C# 无法通过JsonUtility读取JSON
我正在从服务器中提取Json数据,并打算将其读入配置文件。 代码直接运行到C# 无法通过JsonUtility读取JSON,c#,json,unity3d,C#,Json,Unity3d,我正在从服务器中提取Json数据,并打算将其读入配置文件。 代码直接运行到userProfile1=JsonUtility.FromJson(www.text)并停止。我试着在前后放置调试行,但后调试从不触发 我认为这个问题可能与Unity的JsonUtility对数据格式的期望有关,但我不确定具体是什么,因为我没有收到任何错误 string baseurl = "http://55.55.55.55/api/"; public string loginId = "test@spam.com";
userProfile1=JsonUtility.FromJson(www.text)代码>并停止。我试着在前后放置调试行,但后调试从不触发
我认为这个问题可能与Unity的JsonUtility对数据格式的期望有关,但我不确定具体是什么,因为我没有收到任何错误
string baseurl = "http://55.55.55.55/api/";
public string loginId = "test@spam.com";
public UserProfile userProfile1;
void Start()
{
userProfile1 = new UserProfile();
StartCoroutine(GetUserProfile(loginId));
}
IEnumerator GetUserProfile(string email)
{
string url = baseurl + "users/email/" + email;
// Call server
WWW www = new WWW(url);
yield return www;
// Read returned user profile
if (www.error == null)
{
userProfile1 = JsonUtility.FromJson<UserProfile>(www.text);
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
以下是www.text
[
{
"_id":"58b92a058f9565e76d364437",
"first_name":"Test",
"last_name":"Name",
"email":"tinkle@spam.com",
"nick":"Tinkle",
"age":42,
"sex":"male",
"__v":0,
"inventory_slot":200000,
"join_date":"2017-02-26T00:36:10.266Z"
}
]
你的模型没有问题。我认为www.text
一点价值都没有。它可能仍然是null
,因为数据尚未到达。我建议你应该这样做:
IEnumerator GetUserProfile(string email, Action<string> complete)
{
string url = baseurl + "users/email/" + email;
// Call server
WWW www = new WWW(url);
yield return www;
complete(www.text);
}
IEnumerator GetUserProfile(字符串电子邮件,操作完成)
{
字符串url=baseurl+“用户/电子邮件/”+电子邮件;
//呼叫服务器
WWW=新的WWW(url);
收益率;
完成(www.text);
}
您应该将Start例程更改为:
StartCoroutine(GetUserProfile(loginId, (data) =>
{
var userProfile1 = JsonUtility.FromJson<UserProfile>(data);
}));
start例程(GetUserProfile(loginId,(数据)=>
{
var userProfile1=JsonUtility.FromJson(数据);
}));
希望有帮助
p.S.或者你知道吗,我开始认为问题在于你通过了一个列表。尝试将JsonUtility.FromJson(数据)
更改为JsonUtility.FromJson>(数据)
这是服务器发送的json数组。Dostring myJson=www.error
然后通过执行以下操作来修复json以与JsonHelper
一起工作:myJson=fixJson(myJson)代码>。现在,您可以执行UserProfile[]userProfile1=JsonHelper.FromJson(myJson)代码>。您可以在重复问题中提供的答案中找到fixJson
函数和JsonHelper
类。
StartCoroutine(GetUserProfile(loginId, (data) =>
{
var userProfile1 = JsonUtility.FromJson<UserProfile>(data);
}));