[英]Newtonsoft json deserialization - key as property
I have a json file : 我有一个json文件:
...
"Key1": {
"Base": 123,
"Max": 1234
},
"Key2": {
"Base": 123,
"Max": 1234
},
"Key3": {
"Base": 123,
"Max": 1234
},
...
I need to deserialize it into an object with JsonConvert.DeserializeObject<T>(__json);
我需要使用
JsonConvert.DeserializeObject<T>(__json);
将其反序列化为一个对象JsonConvert.DeserializeObject<T>(__json);
But I need to use the keys (Key1, Key2, Key3,...) as a property of my deserialized object. 但是我需要将键(Key1,Key2,Key3等)用作反序列化对象的属性。 Unfortunately, I can't use an alternate deserialization method and I can't modify the json format.
不幸的是,我无法使用其他反序列化方法,也无法修改json格式。
My object is like that 我的对象就是这样
public class Item {
public string Id { get; set; }
public int Base { get; set; }
public int Max { get; set; }
}
My Id's should be "Key1", "Key2, ... 我的ID应该是“ Key1”,“ Key2 ...”
is it possible? 可能吗?
Make a custom Key
class: 制作一个自定义的
Key
类:
public class Key {
public int Base { get; set; }
public int Max { get; set; }
}
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: 然后将JSON结果中的每个项目存储在
Dictionary
,其中的键是键名,其值是Key
项:
var keyCollection = new Dictionary<string, Key>();
//you can then do stuff such as:
var maxOfKeyOne = keyCollection["Key1"].Max;
var baseOfKeyTwo = keyCollection["Key2"].Base;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.