I have the following JSON:
{
"data":[{
"from": "2017-11-22T10:00Z",
"to": "2017-11-22T10:30Z",
"intensity": {
"forecast": 322,
"actual": 343,
"index": "high"
}
}]
}
Of which I want to extract the intensity properties as a KeyValuePair
list.
What I did to access the list:
JObject parsed = JObject.Parse(JSON);
var list = parsed.SelectToken("data[0].intensity").ToList();
This gives me the following list of JToken objects:
"forecast": 322
"actual": 343
"index": "high"
How can I convert this to a KeyValuePair<string, string>
list?
After some extra searching I found the following post that gave the hint for the final solution: Get Name of JObject in json.net using Linq
I implemented the following solution:
var parsed = JObject.Parse(JSON);
var list = parsed.SelectToken("data[0].intensity");
List<KeyValuePair<string, string>> keyvaluelist = new List<KeyValuePair<string, string>>();
foreach (var item in list)
{
JProperty prop = (JProperty)item;
string key = prop.Name;
string value = (string)prop.Value;
keyvaluelist.Add(new KeyValuePair<string, string>(key, value));
}