【问题标题】:Get the json object count inside the json array获取 json 数组中的 json 对象计数
【发布时间】:2018-04-03 06:29:05
【问题描述】:

从下面的 json 响应中,视图数组包含多个对象。 放心使用如何在视图数组中迭代 json 对象

使用的代码

Response response = RestAssured.given().when().get(getURL);
  ArrayList<Map<String,Object>> jsonList = response.jsonPath().get("views");
  jsonList.size();
  //It returns size 1


[{
        gameIfd: 2018916,
        gameIdGlobal: 1948141,
        views: [{
                name: "Preview",
                displayOrder: 1,
                groups: [],
                actions: [],
                localizedName: {}
            },{
                name: "Thumbnail",
                displayOrder: 2,
                groups: [],
                actions: [],
                localizedName: {}
            }

        ]
    }
]

【问题讨论】:

  • 使用 Jackson 转换器,您可以将 json 转换为 pojo,然后您可以对其进行迭代。我不确定是否放心。
  • 你的json不正确
  • jsonlint.com你的json不正确

标签: java json rest rest-assured


【解决方案1】:

我是这样找到的

Response response = RestAssured.given().when().get(getURL);
JsonPath pathResponse = response.jsonPath();
List<String> key = pathResponse.getList("views[0]");

  System.out.println(key.size()); //Whcih prints the jsonobjects inside views array

【讨论】:

    【解决方案2】:

    您的主要 JSON 响应是一个列表。因此,当您调用 response.jsonPath().get("views") 时,它会为您提供主列表中所有对象的所有 views 列表。而不是分配给ArrayList&lt;Map&lt;String, Object&gt;&gt;,您应该将其分配给ArrayList&lt;ArrayList&lt;Map&lt;String,Object&gt;&gt;&gt;,如下所示:

         ArrayList<ArrayList<Map<String,Object>>> jsonList = 
                                           response.jsonPath().get("views");
    

    那么你可以得到first对象的views列表为:

    jsonList.get(0).size()
    

    并且response.jsonPath().get("views[0]") 还为您提供第一个对象的views 列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多