如何从这个Json中提取所有的值进行断言?

问题描述 投票:0回答:1

我的json响应是一个字符串。我试图写一个通用的断言方法来检查一个属性名是否等于正确的值。我无法提取所有的json。在Children token中,只有第一组。我怎样才能得到这个validation.{ "id": 5, "name": "NoTag", "type": 0, "query": null, "parentId": null, "ownerId": null, "activeDirectoryId": null, "hasChildren": false }。

"[
  {
    "id": 5,
    "name": "NoTag",
    "type": 0,
    "query": null,
    "parentId": null,
    "ownerId": null,
    "activeDirectoryId": null,
    "hasChildren": false
  },
  {
    "id": 6,
    "name": "NewTag",
    "type": 0,
    "query": null,
    "parentId": null,
    "ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
    "activeDirectoryId": null,
    "hasChildren": false
  },
  {
    "id": 7,
    "name": "JohnTag",
    "type": 0,
    "query": null,
    "parentId": null,
    "ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
    "activeDirectoryId": null,
    "hasChildren": false
  },
  {
    "id": 10,
    "name": "MyTag",
    "type": 0,
    "query": null,
    "parentId": null,
    "ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
    "activeDirectoryId": null,
    "hasChildren": false
  }
]"

/这里是我的断言方法。

public static void VerifyJsonString(IRestResponse response, string Property, string Value)
        {
            var res = response.Content; //using Restsharp 

            JArray jsonObject = JArray.Parse(response.Content);
            foreach (JObject content in jsonObject.Children<JObject>())
            {
                foreach (JProperty prop in content.Properties().Where(p => p.Name == Property))
                {
                    Assert.That(prop.Value, Is.EqualTo(Value));
                }
            }
        }

c# json restsharp
1个回答
0
投票

你可以使用下面的代码从JSON数组中获取每个元素的属性名。

        JArray jArray = JArray.Parse(response.Content);
        foreach (var element in jArray)
        {
            var propName = element["name"];
            Assert.That(prop.Value, Is.EqualTo(propName));
        }
© www.soinside.com 2019 - 2024. All rights reserved.