Json.Net Changing from JObject loops to JArray
16,919
Solution 1
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);
}
}
}
Solution 2
Or easy way would be to do just loop through it like this.
JObject json = JObject.Parse(text);
foreach (var id in json["bank"])
{
// your condition here
if(id["epName"]=="FRED001")
Console.WriteLine(id);
}
Related videos on Youtube
Author by
PhilH
Updated on September 15, 2022Comments
-
PhilH over 1 year
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
? -
PhilH over 9 yearsWow, excellent. It's easy when you know how. Thanks. To extend this further, say I wanted to also retrieve "name": "bank 1", could I do this by editing the 'var ids'?
-
PhilH over 9 yearsThink I might have figured it out:
var ids = from bank in json["bank"] from endpoint in bank["endpoints"] where (string) endpoint["epName"] == "FRED001" select new { epId = (string)endpoint["epId"], bankName = (string)bank["name"], }; foreach (var id in ids) { Console.WriteLine(id.epId); Console.WriteLine(id.bankName); }
-
Jon Skeet over 9 years@PhilH: Sorry, didn't see the edit to your comment - but yes, that's basically it.
-
beast over 6 years@JonSkeet performance-wise, lync query is better or using two for-loops?