singisu
singisu

Reputation: 11

Extracting data from JSON structure in C#

JSON data:

{
    "return": {
        "output01": "Test request success!!",
        "output02": "test request"
    }
}

C# code:

JObject obj = JObject.Parse(jsonString);
JToken jToken = obj["return"];

foreach (JToken item in jToken)
{
     string output1_param = item["output01"].ToString();
     string output2_param = item["output02"].ToString();
}

Think of a repeat case.

System.InvalidOperationException: 'Cannot access child value on Newtonsoft.Json.Linq.JProperty.'

What's wrong?

Upvotes: 0

Views: 568

Answers (2)

Guru Stron
Guru Stron

Reputation: 141680

item is a JProperty, so it does not support indexer by object key (for example string one). You need either strip foreach:

JToken jToken = obj["return"];
string output1_param = jToken["output01"].ToString();
string output2_param = jToken["output02"].ToString();

Or work with Values of item, for example via First:

foreach (JToken item in jToken)
{
    Console.WriteLine(item.First.ToString());
}

Also in this case casting to JProperty in foreach is also an option:

foreach (JProperty item in jToken)
{
    Console.WriteLine($"{item.Name} - {item.Value}");
}

Upvotes: 3

mostafa
mostafa

Reputation: 289

as you can see in This Link, indexer of JToken does not implemented and your code tries to using indexer of JToken.

When you call GetEnumerator of jToken, in this sample you will get just single element which is JProperty, so calling indexer of JProperty(by using string key) which implemented JToken will try using this indexer and throws exception.

what happens if you call using this way:

jToken["output01"].ToString();

in this pattern you are using indexer of JObject, which iterates over ChildrenTokens of JObject and give you values.

as Guru said you must read value using value field or use First element.

Upvotes: 0

Related Questions