我创建了一个简单的类模型(AnchorMetaData
),如下所示,其中有两个项目。一个是列表字段(Vector3
),由于它的制作方式而无法序列化,因此我为类(SerializableVector3
)创建了可以序列化和反序列化的属性。我希望与Newtonsoft一起使用此属性来保存/加载模型。
该类保存得很好,但是,当我尝试从JSON反序列化模型时,它会调用AttachedTaskLocations
属性的getter而不是setter。这使得要初始化的字段为空。
我仅通过使用日志消息并设置一些断点来注意到这一点。反序列化时,它从不调用setter。这很奇怪,因为它应该起作用。
另一个奇怪的行为是,它确实使用文件中的正确值在SerializableVector3
的x,y,z的设置器上暂停。这太奇怪了。
我正在使用Unity 2019.1.14,但这也可以在没有它的情况下工作,只需将向量列表更改为您拥有的东西即可。
当我加载显示的JSON文件时,该文件是通过序列化AnchorMetaData
创建的,它在attachedTaskLocations
中有零个项目。为什么会这样呢?为什么二传手没被叫到?
我为保存/加载Vector3
创建的类称为SerializableVector3
。
我要保存/加载的班级:
[Serializable]
public class AnchorMetaData
{
// Cannot serialize this.
[JsonIgnore]
public List<Vector3> attachedTaskLocations = new List<Vector3>();
/// <summary>
/// This property servers as an interface for JSON de-/serialization.
/// It uses a class that can be serialized by Newtonsoft.
/// Should not be used in code except for serialization purposes.
/// </summary>
[JsonProperty("AttachedTaskLocations")]
public List<SerializableVector3> AttachedTaskLocations
{
get
{
Debug.Log("Writing serialized vector.");
return attachedTaskLocations
.Select(vector3 => new SerializableVector3(vector3))
.ToList();
}
set
{
Debug.Log("Loading serialized vector.");
attachedTaskLocations = value
.Select(sVector3 => new Vector3(sVector3.x,sVector3.y,sVector3.z))
.ToList();
}
}
}
序列化JSON:
{
"AttachedTaskLocations": [
{
"x": 1.0,"y": 1.0,"z": 1.0
},{
"x": 1E+12,"y": 2.0,"z": 3.0
},{
"x": 0.0,"y": 0.0,"z": 0.0
}
]
}