如何在C#中计算数组中JSON元素的数量

kzmpq1sx  于 2023-06-25  发布在  C#
关注(0)|答案(2)|浏览(233)

我正在使用instagram API,当我收到带有任何标签的最新媒体时,这个模板:https://api.instagram.com/v1/tags/ {hashtag}/media/recent我收到的数据如下:

{
  "pagination": {
    "next_max_tag_id": "any_number",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "any_number",
    "next_min_id": "any_number",
    "min_tag_id": "any_number",
    "next_url": "https://api.instagram.com/v1/tags/{hashtag}/media/recent?access_token={my_personal_access-token}"
  },
  "meta": {
    "code": 200
  },
  "data": [
    {
      "attribution": null,
      "tags": [
        "any_tag",
        "any_tag1",
        "any_tag2",
        "any_tag3"
      ],
      "type": "image",
      "location": null,
      "comments": {
        "count": 0,
        "data": []
      },
      "filter": "Normal",
      "created_time": "any_number",
      "link": "any_url",
      "likes": {
        "count": 0,
        "data": []
      },
      "images": {
        "low_resolution": {
          "url": "any_url",
          "width": 320,
          "height": 320
        },
        "thumbnail": {
          "url": "any_url",
          "width": 150,
          "height": 150
        },
        "standard_resolution": {
          "url": "any_url",
          "width": 640,
          "height": 640
        }
      },
      "users_in_photo": [],
      "caption": {
        "created_time": "any_number",
        "text": "any_content",
        "from": {
          "username": "any_username",
          "profile_picture": "any_url",
          "id": "any_number",
          "full_name": "any_full_name"
        },
        "id": "any_number"
      },
      "user_has_liked": false,
      "id": "any_number",
      "user": {
        "username": "any_username",
        "profile_picture": "any_url",
        "id": "any_number",
        "full_name": "any_full_name"
      }
    },

如你所见,对象“data”是一个数组,进一步我们可以看到对象“tags”,它也是一个数组。如何在C#中检查数组中数组元素数目?我试过这样:

JArray items = (JArray)jsonData["data[0].tags"];
            int length = items.Count;

但它不起作用我像这样解析JSON:

dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(JSON_string);
olqngx59

olqngx591#

var token = JToken.Parse(str);
var data = token.Value<JArray>("data");
var tags = data[0].Value<JArray>("tags");
var count = tags.Count;

您也可以使用JsonPath

var token = JToken.Parse(str);
var count = token.SelectTokens("$.data[0].tags[*]").Count();
wdebmtf2

wdebmtf22#

当我发现这个问题时,我正在研究一个类似的问题。我碰巧发现了一个稍微不同的解决方案,使用System.Text.Json,我认为这可能对任何像我一样偶然发现这个问题的人都有用:

var jsonObject = JsonNode.Parse(str) as JsonObject;
var tags = jsonObject["data"][0]["tags"] as JsonArray;
var tags = tags.Count;

相关问题