首页 > 解决方案 > 如何访问数组列表并使用 AND 条件验证值

问题描述

我得到的回复如下:

{
    "cartId": "default",
    "cartLines": [
        {
            "testid": "123",
            "isDeleted": false,
            "name": "peter",
        },
        {
            "testid": "123",
            "isDeleted": true,
            "name": "mary",
        }
    ],
    "type": "test"
}

我想确保 "name": "peter" 查询条件何时为"testid": "123" AND "isDeleted": false

我可以使用什么类?java 或 groovy 脚本语言都很好。

这是我做断言的常用方式,直截了当。println(test_info) 返回我在上面给出的响应。

现在我想用于更多条件。

//SQL statement
String dbQuery2 = /SELECT * FROM public.tests where test_id = 'default'/


//Connect to PostgresSQL, global variable is stored at profile
List results = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.dbConnString2 , GlobalVariable.dbUsername2 , GlobalVariable.dbPassword2 ,GlobalVariable.dbDriver2 ,dbQuery2 )
println(results)


//print the "test_info" column
String test_info = results.get(0).get('test_info')
println(test_info)

//convert to json format and verify result
def test_infojson = new JsonSlurper().parseText(new String(test_info))
println('Database test_info response text: \n' + JsonOutput.prettyPrint(JsonOutput.toJson(test_infojson)))

assert test_info.contains("peter")

标签: javagroovy

解决方案


下面的解决方案是在java中:

您需要一个类来表示您的 JSON 结构。

class Response {
  String cardId;
  String type;
  List<Cartline> cartlines;

  //Constructor

  //Getters and Setters

}

class Cartline {
  String name;
  String testid;
  boolean isDeleted;

  //Constructor

  //Getters and Setters
}

然后在您的主代码中,您可以执行如下所示的操作:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);

JSONArray arr = obj.getJSONArray("cartLines");
for (int i = 0; i < arr.length(); i++)
{
    String name = arr.getJSONObject(i).getString("name");
    String testId = arr.getJSONObject(i).getString("testId"); 
    Boolean isDeleted = arr.getJSONObject(i).getBoolean("isDeleted");

 if (name.equals("peter") && testId. equals("123") && isDeleted == false) {
      // do your stuff
  }
}

您可以在此处访问 jar 文件:http: //mvnrepository.com/artifact/org.json/json


推荐阅读