【问题标题】:Java Rest Assured how to update value of nested json object?Java Rest Assured 如何更新嵌套 json 对象的值?
【发布时间】:2020-02-12 06:50:56
【问题描述】:

我有一个这样的 json:

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "documentDate": "05-02-2020",
        "tenantBillingAddr": null,
        "code": "0000"
      } 
}

我需要将“code”值(即“0000”)替换为“1234” 我尝试通过引用此Building a nested JSONObject

来关注
JSONObject requestParams = Utilities.readJSON("MyFile.json");
JSONObject childJSON = new JSONObject();
childJSON.put("code", "1234");
requestParams.put("exportDocumentRequest", childJSON);

但它给了我这样的输出:

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "code": "0000"
      } 
}

它正在删除“exportDocumentRequest”中的其他子字段。我需要它像这样更新“代码”:

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "documentDate": "05-02-2020",
        "tenantBillingAddr": null,
        "code": "1234"
      } 
}

【问题讨论】:

    标签: java json rest-assured-jsonpath


    【解决方案1】:

    你应该使用扩展运算符来做。

    扩展运算符复制值,您可以显式更新所需的值。就像我将code 更改为5000

    let test = {
      "application": "ERP",
      "subject": "Quote 0000005 from TestSG",
      "exportDocumentRequest": {
        "documentDate": "05-02-2020",
        "tenantBillingAddr": null,
        "code": "0000"
      }
    }
    
    let updated_test = {
      ...test,
      "exportDocumentRequest": {
        ...test.exportDocumentRequest,
        "code": "5000"
      }
    }
    
    console.log(updated_test)

    【讨论】:

    【解决方案2】:

    How to edit, modify nested JSONObject 的副本

    以下对我有用。

    requestParams.getJSONObject("exportDocumentRequest").put("code", "1234");
    

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多