ThePHPAddicted ThePHPAddicted - 1 year ago 194
JSON Question

C# deserialize Json unknown keys

I have this JSON and i have to deserialize it:

"homepage": "",
"promos": {
"1.10-latest": "",
"1.10.2-latest": "",
"1.10.2-recommended": "",
"1.5.2-latest": "",
"1.5.2-recommended": "",
"1.6.1-latest": "",
"1.6.2-latest": "",
"1.6.2-recommended": "",
"1.6.3-latest": "",
"1.6.4-latest": "",
"1.6.4-recommended": "",
"1.7.10-latest": "",
"1.7.10-latest-1.7.10": "",
"1.7.10-recommended": "",
"1.7.2-latest": "",
"1.7.2-recommended": "",
"1.8-latest": "",
"1.8-recommended": "",
"1.8.8-latest": "",
"1.8.9-latest": "",
"1.8.9-recommended": "",
"1.9-latest": "",
"1.9-recommended": "",
"1.9.4-latest": "",
"1.9.4-recommended": "",
"latest": "",
"latest-1.7.10": "",
"recommended": ""

Searching on this website a lot, i came out with this code:

dynamic json = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
foreach (KeyValuePair<string, string> entry in json["promos"])

I need to get both Key and Value from that Json but with this code it says there is an unexpected character on line 3 pos 13.
I tried in a lot of different ways but i can't get value and key at the same time. With some code i got just the key and with some other code i got just the value. Can you explain me how to obtain both value and key?

Answer Source

You can directly parse the json as JObject and convert the node "promos" to Dictionary

var json = JObject.Parse(data);
var promos = json["promos"].ToObject<Dictionary<string, string>>();
foreach (var entry in promos)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download