Json.NET: Deserializing nested dictionaries

前端 未结 3 492
野的像风
野的像风 2020-12-01 02:49

When deserializing an object to a Dictionary (JsonConvert.DeserializeObject>(json)) nested objects are deser

3条回答
  •  一向
    一向 (楼主)
    2020-12-01 03:23

    I found a way to convert all nested objects to Dictionary by providing a CustomCreationConverter implementation:

    class MyConverter : CustomCreationConverter>
    {
        public override IDictionary Create(Type objectType)
        {
            return new Dictionary();
        }
    
        public override bool CanConvert(Type objectType)
        {
            // in addition to handling IDictionary
            // 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>(
                json, new JsonConverter[] {new MyConverter()});
        }
    }
    

    Documentation: CustomCreationConverter with Json.NET

提交回复
热议问题