Home > database >  How to deserialize Json to a simple Dictionary
How to deserialize Json to a simple Dictionary

Time:10-08

I have a json file like:

[
  {
    "Id": "Id1",
    "Value": "Value1"
  },
  {
    "Id": "Id2",
    "Value": "Value2"
  },
  {
    "Id": "Id3",
    "Value": "Value3"
  }
]

I need to move it to a simple Dictionary(string, string) and the id should be a key and value - value.

I can trim it and use JsonDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); but I think there should be more simple way.

CodePudding user response:

public class JsonItem
{
    public string Id;
    public string Value;
}

var result = JsonConvert.DeserializeObject<List<JsonItem>>(json).ToDictionary(k => k.Id, v => v.Value);

You can check live demo here: https://dotnetfiddle.net/P8vONj

CodePudding user response:

You can achieve that with the following simple command:

var result = JArray.Parse(json).ToDictionary(token => token["Id"], token => token["Value"]);

UPDATE

Thanks for @Jamiec to pointing out my result's type is Dictionary<JToken, JToken>.

Dictionary<string, string> result = JArray.Parse(json)
    .ToDictionary(token => (string)token["Id"], token => (string)token["Value"]);
  • Related