如何替换存储在JSON文件中的JSON值并在Rest-Assured测试中使用该值

如何替换存储在JSON文件中的JSON值并在Rest-Assured测试中使用该值,json,rest-assured,rest-assured-jsonpath,Json,Rest Assured,Rest Assured Jsonpath,我在JSON中有一组输入数据文件,我试图替换JSON文件中的一个值,并使用该值在restAssured中执行post请求 JSON文件具有 { "items": [ { "item_ref": 241, "price": 100 } ] } 下面的jsonbody是上述JSON文件的字符串 这是失败的代码: JSONObject jObject = new JSONObject(jsonbody)

我在JSON中有一组输入数据文件,我试图替换JSON文件中的一个值,并使用该值在restAssured中执行post请求

JSON文件具有

{
    "items": [
        {
            "item_ref": 241,
            "price": 100
        }
    ]
}
下面的jsonbody是上述JSON文件的字符串

这是失败的代码:

JSONObject jObject  = new JSONObject(jsonbody);
        jObject.remove("item_ref");
        jObject.put("item_ref","251");
        System.out.println(jObject);
这就是我得到的:

{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
我想要的是
{“items”:[{item\u ref:251,“price”:100}}}

我也试过了

JSONObject jObject  = new JSONObject(jsonbody);
        jObject.getJSONObject("items").remove("item_ref");
        jObject.getJSONObject("items").put("item_ref","251");
        System
但是它说JSONObject[“items”]不是JSONObject

我只需要把241换成251。有没有更简单的方法


一般来说,如果我们有一个预定义的JSON主体文件,并且如果我们想替换主体中的一些值,并在RestAssured内的POST调用中使用这些值,那么有没有更简单的方法呢?

问题在于-field
item\u ref
price
并不像您想象的那样位于JSON对象中。 它们位于包含JSON对象的JSON数组中。为了修改该值,您必须获取数组的元素,然后执行与您编写的代码非常相似的代码

看看这个:

JSONObject jObject  = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
输出为:

{"items":[{"item_ref":251,"price":100}]}

此外,您还可以创建哈希映射:

    HashMap<String,String> map = new HashMap<>();
    map.put("key", "value");

    RestAssured.baseURI = BASE_URL;
    RequestSpecification request = RestAssured.given();
    request.auth().preemptive().basic("Username", "Password").body(map).put("url");
    System.out.println("The value of the field after change is: "  + map.get("key"));
HashMap map=newhashmap();
地图放置(“键”、“值”);
RestAssured.baseURI=BASE\u URL;
RequestSpecification request=restasured.given();
request.auth().preemptive().basic(“用户名”、“密码”).body(映射).put(“url”);
System.out.println(“更改后字段的值为:”+map.get(“key”));

@Mihir接受我的答案:)检查how@Mihir我花时间回答你的问题。让我至少在报答中获得一些声誉,为没有早点这么做而道歉。我已经接受了你的回答。谢谢。你能帮我解决另一个问题吗@米希尔:当然。我在上面