Here is my JSON which I have parsed to a JObject. Can I get the string array for ExternalRateId
from the below using SelectToken
?
As of now, I'm using foreach()
to loop through and get the list of them and converting it to a string. Can we solve this in much easier way using SelectToken()
. If so please show me the best way to do this.
{
"RateCards": [
{
"ExternalRateCardId": "62283ab4",
"Rates": [
{
"ExternalRateId": "2a77db10",
}
],
"IsUpdate": false
},
{
"ExternalRateCardId": "f6878b23",
"Rates": [
{
"ExternalRateId": "2a739550",
}
],
"IsUpdate": false
},
{
"ExternalRateCardId": "3f51162c",
"Rates": [
{
"ExternalRateId": "2a751bf0",
}
],
"IsUpdate": false
}
]
}
CodePudding user response:
you can use LINQ
List<string> externalRateIds = ((JArray)JObject.Parse(json)["RateCards"])
.SelectMany(x => x["Rates"].Select(x => (string)x["ExternalRateId"]))
.ToList();
or if you want a weird syntax with SelectToken
string[] externalRateIds = ((JArray)JObject.Parse(json).SelectToken("RateCards"))
.SelectMany(x => x.SelectToken("Rates")
.Select(x => x.SelectToken("ExternalRateId").Value<string>())
.ToArray();