There is already an answer showing you how to use GSON to convert from JSON to POJO and vice versa. While that is the preferred approach from my point of view but, you can also make use of GSON only to add elements to json array.
Assuming that you have your json array string as follow:
String myJsonArray = "["
+ "{\"name\":\"alex\",\"weight\":\"88\"},"
+ "{\"name\":\"Emma\",\"weight\":\"71\"}"
+ "]";
Initialize Gson object as shown below:
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
Convert your json String array to JsonElement as shown below:
JsonElement elements = gson.fromJson(myJsonArray, JsonElement.class);
Once you have JsonElement it contains your json array then you can convert it to JsonArray as shown below:
JsonArray arr = elements.getAsJsonArray();
Now you have your array as JsonArray and you can print them out by iterating through the elements as shown below:
for(JsonElement e: arr) {
System.out.println(e);
}
And that would give you (based on above string):
{"name":"alex","weight":"88"}
{"name":"Emma","weight":"71"}
Let's assume that you want to add a new object to the existing array but, you have the object in the form of json string as follow:
String newObject = "{\"name\":\"Raf\", \"weight\":\"173\"}";
//Creates new JsonElement from json string
JsonElement newElement = gson.fromJson(newObject, JsonElement.class);
Now you can add this element to your existing array as follow:
arr.add(newElement);
Finally you can print your new json array as we did it before:
for(JsonElement e: arr) {
System.out.println(e);
}
And the output you get is
{"name":"alex","weight":"88"}
{"name":"Emma","weight":"71"}
{"name":"Raf","weight":"173"}