问题描述
我当前正在使用Rest-Assured调用API,其响应主体在下面发布。我需要选择一部分响应,即整个WorkItems标签(在第3行),并更新其值需要设置为唯一值的字段“ CorrelationUId”和“ Value”(WorkItemAttributes标签内的节点)。 / p>
更新后的JSON将用作另一个API的主体。 如何使用Rest-Assured和Java实现此目标?
{
"TotalRecordCount": 1,"BatchSize": 500,"WorkItems": [{
"CreatedByApp": "IssueManagement","ItemState": 1,"StackRank": 0,"CorrelationUId": "05c0df91-cd6f-4f74-8e19-0be556879e59","RowStatus": null,"WorkItemDeliveryConstructs": [{
"CreatedByUser": "Gateway","ItemState": 0
}
],"WorkItemLanguages": null,"WorkItemProductInstances": [{
"ModifiedOn": "2020-08-05T05:01:15.335316Z","UserUId": null,"ItemState": 0
}],"WorkItemAssociations": null,"WorkItemAttachments": null,"WorkItemAttributes": [{
"IdValue": "00000000-0000-0000-0000-000000000000","IdExternalValue": "","Value": "enter unique data here","ItemState": 0
},{
"IdValue": "00000000-0000-0000-0000-000000000000","Value": "","ItemState": 0
}
]
}],"Faults": [],"StatusCode": 0,"MergeResult": null
}
下面是上面的代码段。
RequestSpecification request = RestAssured.given();
request.header("Content-Type","application/json")
JSONObject requestParams = new JSONObject();
requestParams.put("data",Property.getProperty("data"));
Response response = request.post(url);
JsonPath js = response.jsonPath();
JSONObject responSEObject = new JSONObject(response.jsonPath().getJsonObject("WorkItems"));
Configuration configuration = Configuration.builder().jsonProvider(new JacksonjsonNodeJsonProvider()).mappingProvider(new JacksonMappingProvider()).build();
DocumentContext json = JsonPath.using(configuration).parse(jsonString);
String jsonPath = "WorkItems.CorrelationUId";
String newValue = "newCorrelationUId";
System.out.println(json.set(jsonPath,newValue).jsonString());
添加了以下依赖性,请放心。但是,我遇到了与jayway依赖项有关的导入冲突“导入io.restassured.path.json.JsonPath与另一个导入语句发生冲突”
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
解决方法
下面的代码片段帮助我使用Jayway更新了节点值并选择了整个json的一部分
DocumentContext json = JsonPath.using(configuration).parse(file);
String jsonPath = "WorkItems[0].WorkItemAttributes[0].Value";
String newValue = "new title";
DocumentContext finaljson = json.set(jsonPath,newValue);
DocumentContext context = JsonPath.parse(finaljson.jsonString());
HashMap<String,Object> requiredpartofJson= context.read("WorkItems[0]");