Newtonsoft.Json Dictionary serialization problem


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 > ?

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!

When the Serialize method is called on a formatter, object serialization proceeds according to the following sequence of rules:

  1. 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.

  2. 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.

  3. If the object is marked appropriately, check whether the object implements the ISerializable interface. If the object does, GetObjectData is called on the object.

  4. If the object does not implement ISerializable, the default serialization policy is used, serializing all fields not marked as NonSerialized.

@Krzysztof-P I’ve run into the same issue trying to deserialize a Dictionary<Vector2Int, Object>. Were you able to sort this out?