In order to achieve what you want, you have to properly reach out to productThirdPartyDetails as shown below, then you have to identify the way of getting JSONObject that needs to be added, I have hardcoded that part it's better to get that object through a method.

JSONObject obj = new JSONObject(additionalThirdParty);


        JSONObject objtobeadded =  new JSONObject();
        objtobeadded.put("thirdPartyId", "TH11");
        objtobeadded.put("Location", "Belgium");
        objtobeadded.put("addtionalInfo", new JSONArray());

        JSONObject assetsObj = obj.getJSONObject("object").getJSONObject("ASSETS");

        JSONArray prodDetailsArr = assetsObj.getJSONArray("productDetails");

        for(int i=0;i<prodDetailsArr.length();i++){            
            JSONArray arr = prodDetailsArr.getJSONObject(i).getJSONArray("productThirdPartyDetails");
            arr.put(objtobeadded);
        }
        System.out.println(obj.toString());
Answer from Nishesh Pratap Singh on Stack Overflow
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonarray
org.json.JSONArray.put java code examples | Tabnine
private JSONArray convertListToJsonArray(Object value) throws InvocationTargetException, IllegalAccessException { JSONArray array = new JSONArray(); List<Object> list = (List<Object>) value; for(Object obj : list) { // Send null, if this is an array of arrays we are screwed array.put(obj != null ?
🌐
TutorialsPoint
tutorialspoint.com › how-to-add-a-json-string-to-an-existing-json-file-in-java
How to add a JSON string to an existing JSON file in Java?
import java.io.*; import java.util.*; import com.google.gson.*; import com.google.gson.stream.*; import com.google.gson.annotations.*; public class JSONFilewriteTest { public static String nameRead; public static void main(String[] args) { try { JsonParser parser = new JsonParser(); Object obj = parser.parse(new FileReader("employee1.json")); JsonObject jsonObject = (JsonObject) obj; System.out.println("The values of employee1.json file:\n" + jsonObject); JsonArray msg = (JsonArray)jsonObject.get("emps"); Iterator<JsonElement> iterator = msg.iterator(); while(iterator.hasNext()) { nameRead = i
Top answer
1 of 3
7

There isnt any problem with your code. It does append

String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);

This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}. Isnt this what you are expecting?

With gson you can do like

import com.google.gson.Gson;
import com.google.gson.JsonObject;


public class AddJson {

    public static void main(String[] args) {
        String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
        Gson gson = new Gson();
        JsonObject inputObj  = gson.fromJson(json, JsonObject.class);
        JsonObject newObject = new JsonObject() ;
        newObject.addProperty("lat", "newValue");
        newObject.addProperty("lon", "newValue");
        inputObj.get("results").getAsJsonArray().add(newObject);
        System.out.println(inputObj);
    }

}
2 of 3
4

Simple Approach

    String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
    System.out.println(jsonData);
    try {
        JSONArray result = new JSONObject(jsonData).getJSONArray("results");
        result.getJSONObject(0).put("city","Singapore");
        jsonData = "{\"results\":"+result.toString()+"}";
        System.out.println(jsonData);
    } catch (JSONException e) {
        e.printStackTrace();
    }

OutPut Before Appending

{"results":[{"lat":"value","lon":"value" }]} 

OutPut After Appending

{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-add-a-jsonarray-to-jsonobject-in-java
How can we add a JSONArray to JSONObject in Java?
July 4, 2020 - We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method. import org.json.*; import java.util.*; public class AddJSONArrayToJSONObjTest { public static void main(String args[]) ...
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-add-a-jsonarray-within-jsonobject-in-java
How can we add a JSONArray within JSONObject in Java?
JavaJSONObject Oriented ... object. We can also add a JSONArray within JSONObject by first creating a JSONArray with few items and add these array of items to the put() method of JSONObject class....
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 67632510 › add-object-to-existing-json-file-java
add object to existing JSON file JAVA - Stack Overflow
May 21, 2021 - ArrayNode array = (ArrayNode) jsonNode.get("carTypes"); //<-- 1) convert the node into ArrayNode ObjectNode objNode = mapper.createObjectNode(); //<-- 2) create a new object node objNode.put("model", "civic"); //<-- add your attributes to the new object node array.put(objNode); //<-- put the new node inside the array
🌐
Stack Overflow
stackoverflow.com › questions › 50039189 › how-to-add-object-to-jsonarray
java - How to add object to JSONArray - Stack Overflow
April 26, 2018 - public class Test { public static void main(String[] args) { Mypojo mypojo = new Mypojo(); Gson gson = new Gson(); JSONArray records = new JSONArray(); for (int i = 0; i < 1; i++) { if (5 > 0) { mypojo.setPoAccount("050017"); mypojo.setPoAmount("12"); JSONObject objects = new JSONObject(gson.toJson(mypojo)); records.put(objects); } mypojo.setPoAccount("050016"); mypojo.setPoAmount("800"); JSONObject objects = new JSONObject(gson.toJson(mypojo)); records.put(objects); } System.out.println(records); } }
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-add-elements-to-json-object-using-json-lib-api-in-java
How to add elements to JSON Object using JSON-lib API in Java?
The JSON-lib is a Java library for serializing and de-serializing java beans, maps, arrays, and collections in JSON format. We can add elements to the JSON object using the element() method of JSONObject class.
🌐
Geeky Hacker
geekyhacker.com › home › java › append arrays to an existing json file with jackson
Append arrays to an existing JSON file with Jackson - Geeky Hacker
June 5, 2024 - import com.fasterxml.jackson.m...writeValue(file, studentsFileContent) A better solution is to read the data page by page and append it to the existing JSON file....
🌐
Stack Overflow
stackoverflow.com › questions › 7487753 › add-json-object-to-existing-json-array
android - Add json object to existing json array - Stack Overflow
DefaultHttpClient client = new DefaultHttpClient(); String finalJson=""; HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); finalJson=EntityUtils.toString(getResponseEntity); System.out.println("getResponse.."+s); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } finalJson=finalJson.substring(source.indexOf("[")+1)+"\"object:\"" ; // your logic to append object Gson gson = new Gson(); parseJsonClass response = gson.fromJson(source, parseJsonClass .class);