Faisal
Faisal

Reputation: 168

Java Rest Assured how to update value of nested json object?

I have a json like this:

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

I need to replace "code" value i.e "0000" to "1234" I tried following by refering this Building a nested JSONObject

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

but it is giving me output like:

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

It is removing other child fields in "exportDocumentRequest". I need it to be like this with updated "code":

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

Upvotes: 0

Views: 2354

Answers (2)

Faisal
Faisal

Reputation: 168

Duplicate of How to edit, modify nested JSONObject

Following worked for me.

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

Upvotes: 0

Zunaib Imtiaz
Zunaib Imtiaz

Reputation: 3119

You should do it with the spread operator.

A spread operator replicates values and you can explicitly update the ones you want. Like i changed code to 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)

Upvotes: 1

Related Questions