Home > Software engineering >  Update Json value in json Array in Java
Update Json value in json Array in Java

Time:11-27

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

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": "[email protected]",
  "modifiedDateTime": "2021-03-31T09:59:48.616Z",
  "modifiedByUser": "[email protected]"
}

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

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

CodePudding user response:

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.

CodePudding user response:

That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.

  • Related