Travis Liew Travis Liew - 1 year ago 105
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:


And want to serialize this into a
, but reverse the dictionary so the fruit is the
and the integers are the
. Any way to achieve that with

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

Answer Source

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

    .ToDictionary(x => x.Value, x => x.Key);