【问题标题】:Can't deserialize JSON in Unity 5.4 using JsonUtility. Child collection is always empty无法在 Unity 5.4 中使用 JsonUtility 反序列化 JSON。子集合始终为空
【发布时间】:2017-03-18 15:52:08
【问题描述】:

模型

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 集合始终为空。

【问题讨论】:

    标签: c# json unity3d unity5


    【解决方案1】:

    调用FromJson后,结果不是null,而是人 集合总是空的。

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

    另外,this.people = new List&lt;People&gt;(); 应该是 this.people = new List&lt;Person&gt;();

    [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);
        }
    }
    

    【讨论】:

    • 我不知道 Unity 中的 { get; set; }“限制”。这解决了这个问题。至于new List&lt;Person&gt;(); 的事情,那只是我错误地命名了变量以使问题在 StackOverlflow 上对用户更友好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多