2011-06-20 157 views
22

将对象反序列化为DictionaryJsonConvert.DeserializeObject<IDictionary<string,object>>(json))时,嵌套对象被反序列化为JObject s。是否有可能强制嵌套对象被反序列化为DictionaryJson.NET:反序列化嵌套字典

回答

32

我发现了一种通过提供CustomCreationConverter落实到所有嵌套对象转换为Dictionary<string,object>

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()}); 
    } 
} 

文档:CustomCreationConverter with Json.NET

-1

替代/更新:

我需要反序列化字典的字典String s和当前的Json.NET(5.0)我没有必要创建一个CustomConverter,我的理由t一起使用(在VB.Net):

JsonConvert.DeserializeObject(Of IDictionary(Of String, IDictionary(Of String, String)))(jsonString) 

或者,在C#:

JsonConvert.DeserializeObject<IDictionary<String, IDictionary<String, String>>(jsonString); 
+1

这不支持被正确地转换递归/未知JSON结构。 –

+0

这不会回答,因为它具体指的是一个固定的嵌套层次 – Javier