1

我目前正在使用 Rest-Assured 调用 API,其响应正文发布在下面。我需要选择响应的一部分,即整个 WorkItems 标记(在第 3 行),并更新需要将其值设置为唯一值的字段“CorrelationUId”和“Value”(WorkItemAttributes 标记内的节点)。

更新后的 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",
                "IdExternalValue": "",
                "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>
4

1 回答 1

0

下面的代码片段帮助我更新节点值并使用 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]");
于 2020-09-23T05:25:06.847 回答