简体   繁体   中英

Newtonsoft json deserialization - key as property

I have a json file :

...
    "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);

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.

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, ...

is it possible?

Make a custom Key class:

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM