-3
string json = "{"httpStatusCode": "OK",
      "count": 10,
      "entities": [
        {
          "responseCode": 200,
          "ResponseCode": 0,
          "headers": null,
          "Headers": null,
          "content": "name1"
        },
        {
          "responseCode": 200,
          "ResponseCode": 0,
          "headers": null,
          "Headers": null,
          "content": "name2"
        }
      ]
    }"

I use this piece of code and can not print out the value of "content" (name1, name2), it will just skip the if statement

JObject o = JObject.Parse(json);
foreach (var element in o["entities"])
    {
        foreach(var ob in element)
        {
            if(ob.toString() == "content")
                Console.WriteLine(ob);
        }
    }

So, how can I print out the name1 and name2? Thank you.

1 Answers1

1

I assume your example code uses Newtonsoft.Json library.

A few modifications to your code could actually make your code work. You need to search your JSON for a property named "content". For this purpose cast your JToken to JProperty type. Then you can access its name and value like this:

JObject o = JObject.Parse(json);
foreach (var element in o["entities"])
{
    foreach (var ob in element)
    {
        if (ob is JProperty prop && prop.Name == "content")
            Console.WriteLine(prop.Value.ToString());
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Jacek
  • 829
  • 12
  • 31