问题描述
当反序列化对象到词典
( JsonConvert.DeserializeObject< IDictionary的<字符串对象>>(JSON)
)嵌套对象序列化,以 JObject
秒。是否有可能迫使嵌套的对象进行反序列化的词典
S'
When deserializing an object to a Dictionary
(JsonConvert.DeserializeObject<IDictionary<string,object>>(json)
) nested objects are deserialized to JObject
s. Is it possible to force nested objects to be deserialized to Dictionary
s?
推荐答案
我发现了一种所有嵌套对象转换为词典&LT;字符串对象&gt;通过提供
CustomCreationConverter
实施
I found a way to convert all nested objects to Dictionary<string,object>
by providing a CustomCreationConverter
implementation:
class MyConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}
public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject
|| reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);
// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText(@"c:\test.json");
var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(
json, new JsonConverter[] {new MyConverter()});
}
}
文件: <一个href=\"http://james.newtonking.com/projects/json/help/index.html?topic=html/CustomCreationConverter.htm\">CustomCreationConverter与Json.NET
Documentation: CustomCreationConverter with Json.NET
这篇关于Json.NET:反序列化的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!