Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JObject structure - How to iterate?

Tags:

json

c#

loops

I hope someone can help me out even though this have properly been answered before i just cant seem to find the answer to this particular. My problem is i don't know how to get the values in the "value section" with c# code

{{
  "error": false,
  "value": [
    {
      "uploadid": "valuevaluevalue",
      "parentid": "othervalue",
      "id": "idvalue",
      "filename": "account.xml",
      "displayname": "account.xml",
      "size": 116,
      "md5": ""
    }
  ]
}}

I tried to use foreach but im confused when the key/value properties are available and what is a child and what is an array.

I've also tried with the jobject.GetValue("Id") but that gets me an error: "Object reference not set to an instance of an object." . I believe its because that element is only in the second set, but i dont know how to "start there".

like image 568
Andreas Avatar asked Dec 14 '22 09:12

Andreas


1 Answers

The first thing to do is understand your structure. It's somewhat odd, because value is actually an array, containing a single object. You should work out what you would want to do if you ever had multiple objects there.

Here's an example which dumps the values from each item of the array. This works after changing the {{ ... }} in your JSON to { ... }.

using System;
using System.IO;
using Newtonsoft.Json.Linq;

public class Test
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        var obj = JObject.Parse(json);
        var valueArray = (JArray) obj["value"];
        // Note: if the array contains non-objects,
        // this will fail
        foreach (JObject value in valueArray)
        {
            Console.WriteLine("Values:");
            foreach (var property in value.Properties())
            {
                Console.WriteLine("  {0}: {1}", property.Name, property.Value);
            }
        }
    }
}

Output:

Values:
  uploadid: valuevaluevalue
  parentid: othervalue
  id: idvalue
  filename: account.xml
  displayname: account.xml
  size: 116
  md5:

To get just the ID, you could use value["id"].

like image 54
Jon Skeet Avatar answered Dec 17 '22 00:12

Jon Skeet