Bhaskar Mishra Bhaskar Mishra - 7 months ago 26
Java Question

Add a new property to a specific json node using gson

I am exploring gson and wanted to check if I can remove and add elements. I have the below json

{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
}
},
"amount": [
{
"amount": 73.704285,
"currency": "USD"
},
"amountagain": {
"amount": 96.791435,
"currency": "USD"
},
"winners": null,
"pgoodId": null,
},


and now I want to add a new element under body like :

{
"header": {
"timeStamp": "2016-02-09T15:22:36.107-08:00",
"uniqueid": "321c5690-1d2e-4403-9c31-029cc47ef660",
},
"body": {
"search": {
"searchId": 9206422282,
"DateFrom": "2016-04-15T00:00:00-07:00",
"DateTo": "2016-06-24T00:00:00-07:00"
"AddANewFieldHere" : **"2016-04-18"**
}
}


when I do

JsonObject jsonObject = new JsonObject();
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader("src/main/resources/search.json"));
jsonObject = jsonElement.getAsJsonObject();
} catch (FileNotFoundException e) {

} catch (IOException ioe){

}

// jsonObject.get("checkin");
jsonObject.addProperty("AddANewFieldHere","2016-04-18");
System.out.print(jsonObject);

}


It adds this property at the end of the document not as I expect under body.

Answer

jsonObject is the root node. You need to navigate to the node you want to modify.

JsonObject body = jsonObject.getAsJsonObject("body");
body.addProperty("AddANewFieldHere","2016-04-18");

From the example output, it looks like want it under the path body/search/searchId not body though:

JsonObject searchId = jsonObject
                .getAsJsonObject("body")
                .getAsJsonObject("search")
                .getAsJsonObject("searchId");
searchId.addProperty("AddANewFieldHere","2016-04-18");
Comments