Ole Albers
Ole Albers

Reputation: 9295

Getting property/object-name from JSON-List in C#

I have the following JSON-String:

{"object":{"4711":{"type":"volume","owner":"john doe","time":1426156658,"description":"Jodel"},"0815":{"type":"fax","owner":"John Doe","time":1422900028,"description":"","page_count":1,"status":"ok","tag":["342ced30-7c34-11e3-ad00-00259073fd04","342ced33-7c34-11e3-ad00-00259073fd04"]}},"status":"ok"}

A human readable screenshot of that data:

JSON-Data

I want to get the Values "4711" and "0815" of that data. I iterate through the data with the following code:

JObject tags = GetJsonResponse();
var objectContainer = tags.GetValue("object");
if (objectContainer != null) {
  foreach (var tag in objectContainer) {
    var property=tag.HowToGetThatMagicProperty();
  }
}

At the position "var property=" I want to get the values "4711".

I could just use String-Manipulation

string tagName = tag.ToString().Split(':')[0].Replace("\"", string.Empty);

but there must be a better, more OOP-like way

Upvotes: 0

Views: 4182

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

If you get the "object" object as a JObject explicitly, you can access the Key property on each member inside of the JObject. Currently objectContainer is a JToken, which isn't specific enough:

JObject objectContainer = tags.Value<JObject>("object");

foreach (KeyValuePair<string, JToken> tag in objectContainer)
{
    var property = tag.Key;

    Console.WriteLine (property); // 4711, etc.
}

JObject exposes an implementation of IEnumerable.GetEnumerator that returns KeyValuePair<string, JToken>s containing the name and value of each property in the object.

Example: https://dotnetfiddle.net/QbK6MU

Upvotes: 1

Jordan Coulam
Jordan Coulam

Reputation: 359

I got the results using this

        foreach (var tag in objectContainer)
        {
            var property = tag.Path.Substring(tag.Path.IndexOf(".") + 1);
            Console.WriteLine(property);
        }
    }
    Console.ReadLine();

}

Upvotes: 1

Related Questions