0

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

2
  • You could deserialize directly into a model of said object, or if your in Model View Controller, you could do a JsonResult with a parameter of the Model to actually pass the information into. Commented Mar 17, 2015 at 15:30
  • @Greg No MVC (but I understand what you meant) :) Because I am only interested in that single string-value I do not want to create objects for the response. Commented Mar 17, 2015 at 15:31

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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();

}

2 Comments

This is similar to OP's method using string manipulation, Didn't realize it was edited at the time of writing my answer
Sorry for that. :) But your answer is a "bit" nicer as it does not uses .ToString()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.