I’m trying to force Newtonsoft.Json library to serialize/deserialize my custom class which contains a Dictionary <Vector2,Object>. However it serializes it in format that cannot be deserialized back and returns an exception:
ArgumentException: Could not cast or convert from System.String to UnityEngine.Vector2.
I believe it should be possible because library handles UnityEngine.Vector2 fine as well as more standard Dictionaries like < string , string > for example.
Small example to be more precise:
When I serialize UnityEngine.Vector2 object it results in string:
"Vector2VariableName": {
"x": 7.0,
"y": 7.0
}
However when I serialize a Dictionary it results with different, incorrect format:
To solve issue of being unable to correct serialize unity-specific types such as Vector2, Vector3, Color, etc. - use this
If there are incorrect serialization of Vector3, Color etc. types when they are keys to a dictionary - use this solution (e.g. serialize List<KeyValuePair<Color, int>> instead (with your type in place of Color))
As you can see I’m only creating Dictionary, adding two example values and then serializing it an deserializing it back. testDictionary variable is filled properly. I do have some serialized string in temp variable. However execution of line 220 throws an exceprion:
When the Serialize method is called on a formatter, object serialization proceeds according to the following sequence of rules:
A check is made to determine whether the formatter has a surrogate selector. If the formatter does, check whether the surrogate selector handles objects of the given type. If the selector handles the object type, ISerializable.GetObjectData is called on the surrogate selector.
If there is no surrogate selector or if it does not handle the object type, a check is made to determine whether the object is marked with the Serializable attribute. If the object is not, a SerializationException is thrown.
If the object is marked appropriately, check whether the object implements the ISerializable interface. If the object does, GetObjectData is called on the object.
If the object does not implement ISerializable, the default serialization policy is used, serializing all fields not marked as NonSerialized.