skip to Main Content

I have Web API dynamic returns as follow:

{
    "result": true,
    "payload": {
        "data": [
            {
                "class": "Platinum",
                "name": "William",
                "title": "Mr."
            },
            {
                "class": "Silver",
                "name": "Susan",
                "title": "Ms."
            },
            {
                "class": "Platinum",
                "name": "Jack",
                "title": "Mr."
            }
        ]
    }
}

I need to determine if that json returning has an array object named "data" and the get it’s parent object (in the above case the parent object is "payload" so I would able to retrieve the array value by using eg.

 (JArray)jo[payload][data]

I need advice, thank you so much in advance

2

Answers


  1. You can use libraries like Newtonsoft.Json to parse and check.

    JObject jObject = JObject.Parse(yourJsonDate);
    if (jObject["payload"] is JObject payload && payload["data"] is JArray data)
    {
        // Access the array values under "data"
        foreach (var item in data)
        {
            Console.WriteLine(item);
        }
    }
    else
    {
        Console.WriteLine("JSON structure doesn't contain expected elements.");
    }
    
    Login or Signup to reply.
  2. you can use somethin like this

         var dataArr = JObject.Parse(json).SelectToken("payload.data");
    
        if (dataArr != null && dataArr.Type == JTokenType.Array)
        {
            foreach (var item in dataArr) {}
            //or
            var data = dataArr.Select(o => new  { Class=o["class"], ...});
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search