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

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

问题描述

当反序列化对象到词典 JsonConvert.DeserializeObject< IDictionary的<字符串对象>>(JSON))嵌套对象序列化,以 JObject 秒。是否有可能迫使嵌套的对象进行反序列化的词典 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?

推荐答案

我发现了一种所有嵌套对象转换为词典&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:反序列化的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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