I have a problem trying to properly serialize/deserialize object with inner dictionary. Dictionary has some custom type PairIntKey
as a key.
Code is the following:
public class MyClassWithDictionary
{
private Dictionary<PairIntKey, List<int>> _myDictionary = new Dictionary<PairIntKey, List<int>>();
public Dictionary<PairIntKey, List<int>> MyDictionary
{
set { _myDictionary = value; }
}
public void AddElementsToMyDictionary(PairIntKey key, List<int> value)
{
_myDictionary.Add(key, value);
}
}
public class PairIntKey : IEquatable<PairIntKey>
{
private int _value1;
private int _value2;
public int Value1
{
get { return _value1; }
}
public int Value2
{
get { return _value2; }
}
public PairIntKey(int value1, int value2)
{
_value1 = value1;
_value2 = value2;
}
public override int GetHashCode()
{
return _value1 + 29 * _value2;
}
public bool Equals(PairIntKey other)
{
if (this == other) return true;
if (other == null) return false;
if (_value1 != other._value1) return false;
if (_value2 != other._value2) return false;
return true;
}
public override string ToString()
{
return String.Format("({0},{1})", _value1, _value2);
}
}
I serialize like this
public void SerializeAndDeserializeMyObject()
{
var myObject = new MyClassWithDictionary();
myObject.AddElementsToMyDictionary(new PairIntKey(1, 1), new List<int> {5});
var contractResolver = new DefaultContractResolver();
contractResolver.DefaultMembersSearchFlags |= BindingFlags.NonPublic;
string serializedItem = JsonConvert.SerializeObject(myObject,
Formatting.Indented,
new JsonSerializerSettings()
{
ContractResolver = contractResolver,
});
var deserializedItem = JsonConvert.DeserializeObject(serializedItem, typeof(MyClassWithDictionary), new JsonSerializerSettings()
{
ContractResolver = contractResolver,
});
}
serializedItem
looks like
{
"_myDictionary": {
"(1,1)": [
5
]
}
}
The problem is that deserializedItem
has empty MyDictionary
member. Its pretty obvious as soon as Json.Net doesn't know how to convert string "(1,1)" into PairIntKey
class instance.
How to do a proper converter for that case? Or it should not be a converter?