模特
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后,结果不为空,但人集合始终为空。
答案 0 :(得分:11)
在调用FromJson之后,结果不是null,而是人 收集总是空的。
那是因为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);
}
}