Newtonsoft JSON反序列化-密钥作为属性 [英] Newtonsoft json deserialization - key as property

查看:106
本文介绍了Newtonsoft JSON反序列化-密钥作为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件:

I have a json file :

...
    "Key1": {
        "Base": 123,
        "Max": 1234
    },
    "Key2": {
        "Base": 123,
        "Max": 1234
    },
    "Key3": {
        "Base": 123,
        "Max": 1234
    },
...

我需要使用JsonConvert.DeserializeObject<T>(__json);

但是我需要将键(Key1,Key2,Key3等)用作我的反序列化对象的属性. 不幸的是,我无法使用其他反序列化方法,也无法修改json格式.

But I need to use the keys (Key1, Key2, Key3,...) as a property of my deserialized object. Unfortunately, I can't use an alternate deserialization method and I can't modify the json format.

我的对象就是这样

public class Item {
    public string Id { get; set; }
    public int Base { get; set; }
    public int Max { get; set; }
}

我的ID应该是"Key1","Key2 ......

My Id's should be "Key1", "Key2, ...

有可能吗?

推荐答案

创建自定义Key类:

public class Key {
    public int Base { get; set; }
    public int Max { get; set; }
}

然后将JSON中的每个项目存储在Dictionary中,其中的键是键名,值是Key项:

Then store each item in the JSON result in a Dictionary where it's key is the key name and it's value is a Key item:

var keyCollection = new Dictionary<string, Key>();

//you can then do stuff such as:
var maxOfKeyOne = keyCollection["Key1"].Max; 
var baseOfKeyTwo = keyCollection["Key2"].Base;

这篇关于Newtonsoft JSON反序列化-密钥作为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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