首页 > 解决方案 > Java Rest Assured 如何更新嵌套 json 对象的值?

问题描述

我有一个这样的json:

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

我需要将“代码”值(即“0000”替换为“1234”)我尝试通过引用此构建嵌套的 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"
      } 
}

标签: javajsonrest-assured-jsonpath

解决方案


您应该使用扩展运算符来执行此操作。

扩展运算符复制值,您可以显式更新所需的值。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)


推荐阅读