Reputation: 23
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.
Upvotes: 2
Views: 226
Reputation: 22679
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"]);
Upvotes: 2
Reputation: 2805
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
Upvotes: 3