Search code examples
c#jsonjson.net

Simple way of querying a JSON in C# using Json.NET


What is the simple way of querying JSON object instead of writing multiple foreachloops?

Sample JSON

{
    "result_index": 0,
    "results": [
       {
          "final": true,
          "alternatives": [
             {
                "delta": 0.9,
                "timestamps": [
                   [
                      "hi",
                      2.55,
                      2.81
                   ]
                ]
             }
          ]
       }
    ]
}

Is there a way to replace multiple following foreach into single foreach

var rawData = JObject.Parse(responseString);
var results = rawData["results"];

    foreach (var item in results)
     {
         foreach (var alternative in item["alternatives"])
          {
            foreach (var timestamp in alternative["timestamps"])
             {
                           
             }
          }
      }

Solution

  • For C# or any other .NET Language I would suggest that you should use the Linq capabilities of the Newtonsoft Library. Have a look at this example here

    As an update to @JonSkeet answer here is a set of working code.

    class Program
        {
            static void Main(string[] args)
            {
                var sample = JsonConvert.DeserializeObject(File.ReadAllText("SampleJSON.json")) as JObject;
    
                var timestamps = (from item in sample["results"]
                                  from alternative in item["alternatives"]
                                  from timestamp in alternative["timestamps"] select timestamp)
                                  .SelectMany(t => t);
                foreach(var ts in timestamps)
                {
                    var working = ts.ToObject<string>() + " - Hello Ts";
                }
    
            }
        }