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

Can't deserialize JSON in Unity 5.4 using JsonUtility. Child collection is always empty

模特

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不为空,但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);
    }
}