count Jarray in C#

758 Views Asked by At

I need to count data from reqst body in httptrigger function.Data is coming as object type. I am deserialisizing the reqd body as shown below.Below are the object type data i am getting in req.body.

{
  "Response": [
    {
      "id": "1",
      "name": "Warburtons Medium Sliced Soft White Bread 400g",
      "description": "Warburtons Medium Sliced White 400G",
      "brand": "Warburtons",
      "ean": "123",
      "mediaStorageKey": "b",
      "maxQuantity": 6,
      "price": 0.95,
      "size": 400,
      "sizeUnits": "Grams"
    },
    {
      "id": "a",
      "name": "Co-op Orvieto Classico 75cl",
      "description": "Co-op Orvieto Classico 75CL",
      "brand": "Co-op",
      "ean": "489",
      "mediaStorageKey": "c",
      "maxQuantity": 6,
      "price": 5.5,
      "size": 75,
      "sizeUnits": "Centilitres"
    },
    {
      "id": "kl",
      "name": "Co Op Garden Peas in Water 290g",
      "description": "Co-op Garden Peas 290G",
      "brand": "Co Op",
      "ean": "678",
      "mediaStorageKey": "f",
      "maxQuantity": 6,
      "price": 0.45,
      "size": 175,
      "sizeUnits": "Grams"
    }
  ]
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic body = JsonConvert.DeserializeObject(requestBody);
             
dynamic data = body["Response"];

Till this i am getting data like below.

{[{"id":"1","name":"b"},{"id":"f","name":"j"}]}

But now i am not able to count these data which gives 2 in this case as i have to apply for loop. Neither Count,Count() is working here. I am getting the below error.

Newtonsoft.Json.Linq.JValue does not contain a definition for Count

2

There are 2 best solutions below

1
On

create a class with these two fields id and name

public class Item {
  public Int Id {get; set;}
  public String Name {get; set;}
}

and specify the type for your deserialized value:

dynamic body = JsonConvert.DeserializeObject(requestBody);
var rows = JsonConvert.DeserializeObject<List<Item>>(body["Response"]);

now you can use rows.Count();

4
On

If you only need to know the amount of entries inside the Response collection then you can simply do that by making use of JObject and JArray:

string rawJson = ...;
JObject semiParsedJson = JObject.Parse(rawJson);
JArray entries = (JArray)semiParsedJson["Response"];
int count = entries.Count;