Travis Liew Travis Liew - 6 months ago 32
JSON Question

C# deserialize json into dictionary and reverse KV

I am trying to deserialize json and reverse the key/value with the least amount of complexity. I have an input json that looks like:

{
"1":"apple",
"2":"banana",
"3":"orange",
"4":"grape"
}


And want to serialize this into a
Dictionary<string,string>
, but reverse the dictionary so the fruit is the
key
and the integers are the
value
. Any way to achieve that with
Newtonsoft.Json
?

var obj = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
// obj.Keys = { "1", "2", "3" }, but I want them to be { "apple", "banana", ... }

Answer

The least complex way would be to just create another dictionary from the one you've deserialised:

JsonConvert.DeserializeObject<Dictionary<string,string>>(json)
    .ToDictionary(x => x.Value, x => x.Key);
Comments