java - 如何访问数组列表并使用 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")
解决方案
下面的解决方案是在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
推荐阅读
- python - 从 IDLE 外部运行 python 并在 cmd 中启用自动完成
- python - 将从 SFTP 下载的文件的编码从 UTF-16 更改为 UTF-16
- python - Python3.7 mlpy 安装错误 - 'PyThreadState {aka struct _ts}' 没有名为 'exc_type' 的成员
- iis - IIS 上的 Cosmos DB 模拟器
- javascript - Javascript 'arr [index]' 返回整个数组而不是单个值
- laravel - 在laravel中发送邮件-不显示错误并且不发送电子邮件
- sql - 有什么方法可以针对两种不同的条件进行不同的选择查询吗?
- javascript - RecordRTC.js - 使用麦克风和扬声器录制屏幕(虚拟输出) - windows + chrome
- java - Groovy Mockito NullPointerException
- sqlite - 通过将持续时间添加到 SQLite 数据库中的开始日期来更新结束日期