- Home /
Newtonsoft.Json Dictionary serialization problem
Hello!
I'm trying to force Newtonsoft.Json librabry 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 librabry 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: "DictionaryName": { "(-9.0, -9.0)": { "StringVariableName": "stringVariableValue" },
Could anyone give me a hint how to properly serialize and deserialize Dictionary < Vector2, Object > ?
https://dzone.com/articles/how-to-serializedeserialize-a-dictionary-object-in-1
When the Serialize method is called on a formatter, object serialization proceeds according to the following sequence of rules:
A check is made to deter$$anonymous$$e 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 deter$$anonymous$$e 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.
https://docs.microsoft.com/en-us/dotnet/standard/serialization/steps-in-the-serialization-process
Answer by Krzysztof-P · Feb 17, 2019 at 09:15 PM
Well, I'm afraid it's not the wrong type issue. Let me demonstrate it on a simple example:
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:
Any other ideas ? Did anyone have similar problem ? Thanks in advance!
Your answer
Follow this Question
Related Questions
Stop specific fields from being serialized by JSON utility 3 Answers
How to protect JSON file game data? 3 Answers
Json Serialization documentation official Unity website - marking it [Serializable] caused error 1 Answer
How does JsonUtility.FromJson() handle Inheritance? 2 Answers
Is it possible to executing object serialization into JSON asynchronously? 1 Answer