不能在Unity 5.4中使用JsonUtility反序列化JSON.子集合总是空的
本文关键字:子集合 JSON 反序列化 JsonUtility Unity 不能 | 更新日期: 2023-09-27 18:16:27
The Model
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集合始终为空。
调用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);
}
}