当从服务器向客户端发送数据时,我试图序列化和反序列化Dictionary<string, int>
类型的属性。
所以如果我序列化这个简化的对象:
class Foo
{
public Dictionary<string, int> Bar { get; set; }
}
我得到这个漂亮的json(使用TypeNameHandling.All):
{
"$type": "Foo",
"Bar": {
"$type": "Dictionary<String, Int32>"
}
}
问题是在反序列化方面,我使用自定义Binder覆盖BindToType来反序列化。但是当这样做时,typeName是不正确的,我得到一个"Dictionary<String"
代替。
public override Type BindToType(string assemblyName, string typeName)
{
if (typeName == "Dictionary<String, Int32>")
{
// I never get here because typeName is "Dictionary<String"
return typeof(Dictionary<string, int>);
}
// ...
}
对于反序列化,您可以这样做-
class customBinder : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var type = Activator.CreateInstance(objectType);
var data = JObject.Load(reader);
var obj = JsonConvert.DeserializeObject(data.ToString(), type.GetType(), new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
}