I'm pulling a JSON feed that looks like this.
{
"bank": [
{
"id": 35,
"name": "bank 1",
"endpoints": [
{
"epId": 407,
"epName": "FRED001"
},
{
"epId": 516,
"epName": "FRED002"
},
{
"epId": 625,
"epName": "FRED003"
}
]
},
{
"id": 32,
"name": "bank 2",
"endpoints": [
{
"epId": 426,
"epName": "HENRY001"
},
{
"epId": 553,
"epName": "HENRY002"
}
]
},
{
"id": 20,
"name": "bank 3",
"endpoints": [
{
"epId": 1802,
"epName": "GEORGE001"
},
{
"epId": 920,
"epName": "GEORGE002"
},
{
"epId": 1052,
"epName": "GEORGE003"
}
]
}
]
}
The end goal is to search using the known epName 'FRED001', and to retrieve the corresponding epId '407, output to a MessageBox.
I can do this in C# by using loops e.g:
JObject jResults = JObject.Parse(jsonfeed);
JToken jResults_bank = jResults["bank"];
foreach (JObject bank in Results_bank)
{
JToken jResults_bank_endpoint = bank["endpoints"];
foreach (JObject endpoint in jResults_bank_endpoint)
{
if (bank["epName"].ToString() == "FRED001")
{
MessageBow.Show(bank["epId"].ToString());
}
}
}
However this doesn't seem like the best way to do it and I'm convinced that I should be doing this in C# by building an array. How can I achieve the same outcome with a JArray
?
There's no need to explicitly loop or change how you're parsing - you can just use LINQ with the JSON:
using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
class Test
{
static void Main(string[] args)
{
string text = File.ReadAllText("Test.json");
JObject json = JObject.Parse(text);
var ids = from bank in json["bank"]
from endpoint in bank["endpoints"]
where (string) endpoint["epName"] == "FRED001"
select (string) endpoint["epId"];
foreach (var id in ids)
{
Console.WriteLine(id);
}
}
}
See more on this question at Stackoverflow