Json.NET:反序列化嵌套字典 [英] Json.NET: Deserializing nested dictionaries

查看:24
本文介绍了Json.NET:反序列化嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将对象反序列化为 Dictionary (JsonConvert.DeserializeObject>(json)) 时,嵌套对象将反序列化为 JObject s.是否可以强制将嵌套对象反序列化为 Dictionary s?

When deserializing an object to a Dictionary (JsonConvert.DeserializeObject<IDictionary<string,object>>(json)) nested objects are deserialized to JObjects. Is it possible to force nested objects to be deserialized to Dictionarys?

推荐答案

我找到了一种方法,通过提供 CustomCreationConverter 将所有嵌套对象转换为 Dictionary> 实施:

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:	est.json");
        var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(
            json, new JsonConverter[] {new MyConverter()});
    }
}

文档:CustomCreationConverter with Json.NET

Documentation: CustomCreationConverter with Json.NET

这篇关于Json.NET:反序列化嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆