我正在尝试在将数据从服务器发送到客户端时序列化和反序列化类型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>);
}
// ...
}
答案 0 :(得分:0)
你可以做这样的事情来反序列化 -
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)
{
}
}