0

我需要在 httptrigger 函数中计算来自请求体的数据。数据作为对象类型出现。我正在反序列化 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 的这些数据,因为我必须申请循环。也没有CountCount()在这里工作。我收到以下错误。

Newtonsoft.Json.Linq.JValue不包含定义Count

4

2 回答 2

1

使用这两个字段创建一个类,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();

于 2021-06-02T19:22:01.583 回答
0

如果您只需要知道Response集合中的条目数量,那么您可以简单地通过使用JObjectand来做到这一点JArray

string rawJson = ...;
JObject semiParsedJson = JObject.Parse(rawJson);
JArray entries = (JArray)semiParsedJson["Response"];
int count = entries.Count;
于 2021-06-03T08:00:20.947 回答