尝试使用内部字典正确序列化/反序列化对象时遇到问题。字典有一些自定义类型PairIntKey
作为键。
代码如下:
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);
}
}
我像这样序列化
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
看起来像
{
"_myDictionary": {
"(1,1)": [
5
]
}
}
问题是deserializedItem
有空MyDictionary
成员。一旦Json.Net不知道如何将字符串“(1,1)”转换为PairIntKey
类实例,它就非常明显了。
如何为这种情况做一个合适的转换器?或者它不应该是转换器?