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

Dav*_*ave 3 c# json unity-game-engine unity5

该模型

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

JSON

{
    "people":
    [{
        "id":1,"name":"John Smith",
        "email":"jsmith@acme.com",
        "displayImageUrl":"http://example.com/"
    }]
 }
Run Code Online (Sandbox Code Playgroud)

代码

string json = GetPeopleJson(); //This works
GetPeopleResult result = JsonUtility.FromJson<GetPeopleResult>(json);
Run Code Online (Sandbox Code Playgroud)

在调用FromJson之后,结果不为null,但people集合始终为空.

Pro*_*mer 12

在调用FromJson之后,结果不为null,但people集合始终为空.

那是因为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道`{get; 组; Unity中的"限制".这解决了这个问题.至于`new List <Person>();`的事情,这只是我误解了变量,使问题在StackOverlflow上更加用户友好.谢谢 (2认同)