英文:
Unity returning null after serializing JSON to object
问题
以下是翻译好的部分:
[System.Serializable]
public class UserData
{
[JsonProperty("uid")] public int UID;
[JsonProperty("email")] public string Email;
[JsonProperty("password")] public string Password;
}
UserData parsedUserData = JsonUtility.FromJson<UserData>(stringUserData);
但是然后 parsedUserData.UID
是 0
,Email
和 Password
是 null
之前它是正常工作的,我不知道发生了什么变化。
我检查了字符串,但在解析后它是 null
。
JSON 数据:
{"uid":1,"email":"user1","password":"password"}
英文:
I am using the object:
[System.Serializable]
public class UserData
{
[JsonProperty("uid")] public int UID;
[JsonProperty("email")] public string Email;
[JsonProperty("password")] public string Password;
}
And converting it using:
UserData parsedUserData = JsonUtility.FromJson<UserData>(stringUserData);
But then the parsedUserData.UID
is 0
, the Email
and Password
are null
It worked before and I don't know what changed.
I checked and the string is fine but after parsing it's null
The JSON:
{"uid":1,"email":"user1","password":"password"}
答案1
得分: 0
发现了问题,JsonUtility.FromJson
与 JsonProperty
不兼容。
为了解决这个问题,我只需要使用 using Newtonsoft.Json;
并将 JsonUtility.FromJson
替换为 .NET 选项 JsonConvert.DeserializeObject
。
最终的代码是:
UserData parsedUserData = JsonConvert.DeserializeObject<UserData>(stringUserData);
希望这对其他遇到这个问题的人有所帮助。
英文:
Found out the problem,
JsonUtility.FromJson
does not work with JsonProperty
To fix this all I had to do it to use using Newtonsoft.Json;
And replace JsonUtility.FromJson
to the .net option JsonConvert.DeserializeObject
The final code is:
UserData parsedUserData = JsonConvert.DeserializeObject<UserData>(stringUserData);
Hopes this help anyone else with this problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论