Reputation: 565
I have following array:
{
"customizedData":[
{
"key":"SubscriptionId",
"value":"xxxxxxxxxxxxxxxx"
},
{
"key":"OfferId",
"value":"xxxxxxxxxxxxxx"
},
{
"key":"SubscriptionName",
"value":"DYNAMICS 365 BUSINESS CENTRAL TEAM MEMBER"
},
{
"key":"Quantity",
"value":"6"
},
{
"key":"Status",
"value":"Suspended"
},
{
"key":"PartnerOnRecord",
"value":"None"
}
]
}
How do I access key the elements:
"key": "SubscriptionName",
"value": "DYNAMICS 365 BUSINESS CENTRAL TEAM MEMBER"
At the moment I use: (string)t["customizedData"][2]["value"]
Are there any better ways?
Upvotes: 0
Views: 365
Reputation: 945
If you are using the Newtonsoft.Json nuget this could be done with a helper function. first use
var jo = JObject.Parse(jsonContent);
to parse, and pass that to the helper function GetValueFromJson(jo, "SubscriptionName", "customizedData")
, using this helper function:
private string GetValueFromJson(JObject jo, string key, string rootKey)
{
var value = jo[rootKey].Children()
.Where(i => i["key"].ToString() == key)
.Select(i => i["value"].ToString())
.FirstOrDefault();
return value;
}
Upvotes: 1
Reputation: 5370
Assuming you are using Json.net and you don't want to create strong type for it so you can use SelectToken with JSONPath:
t.SelectToken("$.customizedData[?(@.key == 'SubscriptionName')].value").ToString();
Upvotes: 1