Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update Json value in json Array in Java

{
  "page": {
    "size": 2,
    "number": 2
  },
  "places": [
    {
      "eventName": "XYZ",
      "createdByUser": "xyz@xyz.com",
      "modifiedDateTime": "2021-03-31T09:59:48.616Z",
      "modifiedByUser": "xyz@xyz.com"
    }   
   ]}

I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.

    public String modifyJson() throws Exception{
    String jsonString =  PiplineJson.payload(PiplineJson.filePath());
    System.out.println(jsonString);
    JSONObject jobject = new JSONObject(jsonString);
    String uu = jobject.getJSONArray("places")
                       .getJSONObject(0)
                       .put("eventName", randomString())
                       .toString();
    System.out.println(uu);
    return uu; 
}

This is what the above code does.

{
  "eventName": "ABCD",
  "createdByUser": "xyz@xyz.com",
  "modifiedDateTime": "2021-03-31T09:59:48.616Z",
  "modifiedByUser": "xyz@xyz.com"
}

I am trying to get the complete json once it updates the eventName filed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "page": {
    "size": 2,
    "number": 2
  },
  "places": [
    {
      "eventName": "ABCD",
      "createdByUser": "xyz@xyz.com",
      "modifiedDateTime": "2021-03-31T09:59:48.616Z",
      "modifiedByUser": "xyz@xyz.com"
    }   
   ]}

>Solution :

The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.

Changing this:

String uu = jobject.getJSONArray("places")
                   .getJSONObject(0)
                   .put("eventName", randomString())
                   .toString();

to

jobject.getJSONArray("places")
       .getJSONObject(0)
       .put("eventName", randomString());
String uu = jobject.toString();

should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading