I created a simple class model (AnchorMetaData
), shown below, in which there are two items. One is a list field (Vector3
) that cannot be serialized due to how it's made so I created a property for class (SerializableVector3
) that could serialize and deserialize. I hoped to use this property with Newtonsoft for saving/loading the model.
The class saves just fine however, when I try to deserialize the model from JSON it calls the AttachedTaskLocations
property's getter rather than setter. That makes the field to be initialized to be empty.
I only noticed this by using logs message and making some breakpoints. It never calls the setter when deserializing. Which is very odd as it should function.
Another odd behaviour is that it does pause on setter of x, y, z of SerializableVector3
with the correct values from the file. This is super odd.
I'm working with Unity 2019.1.14 but this should work without it too, just change vector list to something you have.
When I load the shown JSON file, which was created by serializing AnchorMetaData
it has zero items in attachedTaskLocations
. Why is this happening? Why does the setter not get called?
Class I created to save/load Vector3
is called SerializableVector3
.
Class I wish to save/load:
[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();
}
}
}
Serialized 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
}
]
}