Unity将JSON序列化为对象后返回null。

huangapple go评论116阅读模式
英文:

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.UID0EmailPasswordnull

之前它是正常工作的,我不知道发生了什么变化。

我检查了字符串,但在解析后它是 null

JSON 数据:

{"uid":1,"email":"user1","password":"password"}
英文:

I am using the object:

[System.Serializable]
public class UserData
{
    [JsonProperty(&quot;uid&quot;)] public int UID;
    [JsonProperty(&quot;email&quot;)] public string Email;
    [JsonProperty(&quot;password&quot;)] public string Password;
}

And converting it using:

UserData parsedUserData = JsonUtility.FromJson&lt;UserData&gt;(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:

{&quot;uid&quot;:1,&quot;email&quot;:&quot;user1&quot;,&quot;password&quot;:&quot;password&quot;}

答案1

得分: 0

发现了问题,JsonUtility.FromJsonJsonProperty 不兼容。

为了解决这个问题,我只需要使用 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&lt;UserData&gt;(stringUserData);

Hopes this help anyone else with this problem.

huangapple
  • 本文由 发表于 2023年8月4日 05:13:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定