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

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

最佳答案

我找到了将所有嵌套对象转换为 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()});
    }
}

文档: CustomCreationConverter with Json.NET

https://stackoverflow.com/questions/6416017/

相关文章:

java - 最新的 org.json

c# - 无法使用 Json.net 序列化具有复杂键的字典

javascript - 使用 Asp.Net MVC 和 KnockoutJS 处理日期

java - 是否有将 Java POJO 转换为 JSON 和 XML 的库?

python - 类型错误 : b'1' is not JSON serializable

javascript - 我可以使用空字符串作为对象标识符吗?

javascript - typescript 对象序列化?

python - 将输出序列化为 JSON - ValueError : Circular refe

java - 使用 jackson 删除 JSON 元素

json - 通过身份引用对象的标准方式(例如,循环引用)?