Demonia
Demonia

Reputation: 342

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?

Upvotes: 0

Views: 1541

Answers (1)

trashr0x
trashr0x

Reputation: 6565

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;

Upvotes: 2

Related Questions