我需要计算httptrigger函数中reqst主体的数据。数据以对象类型的形式出现。我正在取消reqd主体的序列化,如下所示。以下是我在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"];
在此之前,我得到的数据如下。
{[{"id":"1","name":"b"},{"id":"f","name":"j"}]}
但现在我无法计算这些数据,在这种情况下给出2,因为我必须申请循环。Count
和Count()
都不在此工作。我得到以下错误。
Newtonsoft.Json.Linq.JValue
不包含Count
的定义
用这两个字段id
和name
创建一个类
public class Item {
public Int Id {get; set;}
public String Name {get; set;}
}
并指定反序列化值的类型:
dynamic body = JsonConvert.DeserializeObject(requestBody);
var rows = JsonConvert.DeserializeObject<List<Item>>(body["Response"]);
现在您可以使用rows.Count();
如果您只需要知道Response
集合中的条目数量,那么只需使用JObject
和JArray
:
string rawJson = ...;
JObject semiParsedJson = JObject.Parse(rawJson);
JArray entries = (JArray)semiParsedJson["Response"];
int count = entries.Count;