gpt4 book ai didi

c# - 无法使用 JsonUtility 在 Unity 5.4 中反序列化 JSON。子集合始终为空

转载 作者:行者123 更新时间:2023-11-30 13:25:45 29 4
gpt4 key购买 nike

模型

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class GetPeopleResult
{
public List<Person> people { get; set; }
public GetPeopleResult()
{
this.people = new List<People>();
}

public static GetPeopleResult CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<GetPeopleResult>(jsonString);
}

}
[System.Serializable]
public class Person
{
public long id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string displayImageUrl { get; set; }

public Person()
{

}
public static Person CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<Person>(jsonString);
}
}

JSON

{
"people":
[{
"id":1,"name":"John Smith",
"email":"jsmith@acme.com",
"displayImageUrl":"http://example.com/"
}]
}

代码

string json = GetPeopleJson(); //This works
GetPeopleResult result = JsonUtility.FromJson<GetPeopleResult>(json);

调用FromJson后,result不为null,但people集合始终为空。

最佳答案

After the call to FromJson, result is not null, but the people collection is always empty.

那是因为 Unity 不支持属性 getter 和 setter。删除 { get; set; }来自您要序列化的所有类,这应该可以修复您的空集合。

此外,this.people = new List<People>();应该是 this.people = new List<Person>();

[System.Serializable]
public class GetPeopleResult
{
public List<Person> people;
public GetPeopleResult()
{
this.people = new List<People>();
}

public static GetPeopleResult CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<GetPeopleResult>(jsonString);
}

}
[System.Serializable]
public class Person
{
public long id;
public string name;
public string email;
public string displayImageUrl;

public Person()
{

}
public static Person CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<Person>(jsonString);
}
}

关于c# - 无法使用 JsonUtility 在 Unity 5.4 中反序列化 JSON。子集合始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429004/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com