小编典典

Json.NET:反序列化嵌套字典

json

将对象反序列化为DictionaryJsonConvert.DeserializeObject<IDictionary<string,object>>(json))时,嵌套对象反序列化为JObjects。是否可以强制将嵌套对象反序列化为Dictionarys?


阅读 319

收藏
2020-07-27

共1个答案

小编典典

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

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

文档:
Json.NET的CustomCreationConverter

2020-07-27