0

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?

6
  • Does this answer your question? Cannot access child value on Newtonsoft.Json.Linq.JProperty -Error happens while checking JObject using LinQ Commented Sep 14, 2021 at 9:28
  • Just out of curiosity: Why not deserialize to a proper model? Commented Sep 14, 2021 at 9:36
  • 2
    jToken["output01"].ToString() would be enough, you don't that foreach loop. Commented Sep 14, 2021 at 9:36
  • cast jToken to JObject and iterate properties? Commented Sep 14, 2021 at 9:37
  • item is already one of the children. They don't have properties output01 or output02. Commented Sep 14, 2021 at 9:39

2 Answers 2

3

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}");
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.