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 OverflowIn 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());
JSONObject assetsObj = obj.getJSONObject("ASSETS"); here the ASSETS is in under object,
So you should write obj.getJSONObject("object").getJSONObject("ASSETS"); to get the ASSETS object.
JSONArray jsonArray = new JSONArray();
for (loop) {
JSONObject jsonObj= new JSONObject();
jsonObj.put("srcOfPhoto", srcOfPhoto);
jsonObj.put("username", "name"+count);
jsonObj.put("userid", "userid"+count);
jsonArray.put(jsonObj.valueToString());
}
JSONObject parameters = new JSONObject();
parameters.put("action", "remove");
parameters.put("datatable", jsonArray );
parameters.put(Constant.MSG_TYPE , Constant.SUCCESS);
Why were you using an Hashmap if what you wanted was to put it into a JSONObject?
EDIT: As per http://www.json.org/javadoc/org/json/JSONArray.html
EDIT2: On the JSONObject method used, I'm following the code available at: https://github.com/stleary/JSON-java/blob/master/JSONObject.java#L2327 , that method is not deprecated.
We're storing a string representation of the JSONObject, not the JSONObject itself
JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());
This works for me.
I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.
here is simple code
List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());
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);
}
}
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"}]}
In order to have this result:
{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}
that holds the same data as:
{
"aoColumnDefs": [
{ "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
{ "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
{ "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
]
}
you could use this code:
JSONObject jo = new JSONObject();
Collection<JSONObject> items = new ArrayList<JSONObject>();
JSONObject item1 = new JSONObject();
item1.put("aDataSort", new JSONArray(0, 1));
item1.put("aTargets", new JSONArray(0));
items.add(item1);
JSONObject item2 = new JSONObject();
item2.put("aDataSort", new JSONArray(1, 0));
item2.put("aTargets", new JSONArray(1));
items.add(item2);
JSONObject item3 = new JSONObject();
item3.put("aDataSort", new JSONArray(2, 3, 4));
item3.put("aTargets", new JSONArray(2));
items.add(item3);
jo.put("aoColumnDefs", new JSONArray(items));
System.out.println(jo.toString());
The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:
JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()
JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);
You need to create a new jsonObj reference with every iteration of the loop:
for (int j = 0; j < X.size(); j++)
{
zBean aBean = (zBean)X.get(j);
jsonObj = new JSONObject();
//^^^^^^^^^^^^^^^^^^^^^^^^^^^ add this line
jsonObj.put(ID,newInteger(aBean.getId()));
jsonObj.put(NAME,aBean.getName());
jsonArray.add(jsonObj);
}
Otherwise you are updating the same instance over and over again, and adding a reference to the same object many times to the array. Since they are all the same reference, a change to one of them affects all of them in the array.
Following will add json obj into json array
public static void main(String[] args) {
JSONArray jsonArray = new JSONArray();
int i = 0;
while(i < 3)
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("Name","Random"+i);
jsonObj.put("ID", i);
jsonArray.put(jsonObj); //jsonObj will be pushed into jsonArray
i++;
}
System.out.println("jsonArray : "+ jsonArray);
}
Output:
jsonArray : [{"ID":0,"Name":"Random0"},{"ID":1,"Name":"Random1"},{"ID":2,"Name":"Random2"}]
.pom has following dependency
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
Use dataToSend.put("profile", JSONArrayProfile) to add profile JSONArray to JSONObject.
Here is the working code. Try this:
try {
JSONObject dataToSend = new JSONObject();
// Profile
JSONArray jsonArrayProfile = new JSONArray();
// Post 1
JSONObject jsonObjectPost1 = new JSONObject();
jsonObjectPost1.put("fbname", "Think Twice Code Once");
jsonObjectPost1.put("content", "felling full");
jsonObjectPost1.put("likes", 1);
jsonObjectPost1.put("comments", 3);
// Post 2
JSONObject jsonObjectPost2 = new JSONObject();
jsonObjectPost2.put("fbname", "Think Twice Code Once");
jsonObjectPost2.put("content", "felling full");
jsonObjectPost2.put("likes", 1);
jsonObjectPost2.put("comments", 3);
// Add post1, post2 jsonObject to profile jsonArray
jsonArrayProfile.put(jsonObjectPost1);
jsonArrayProfile.put(jsonObjectPost2);
// Add profile jsonArray to jsonObject
dataToSend.put("profile", jsonArrayProfile);
Log.d("SUCCESS", "JSON: " + dataToSend.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json build error: " + e.getMessage());
}
OUTPUT:
{
"profile":[
{
"fbname":"Think Twice Code Once",
"content":"felling full",
"likes":1,
"comments":3
},
{
"fbname":"Think Twice Code Once",
"content":"felling full",
"likes":1,
"comments":3
}
]
}
You can use following code to try it.
JSONArray ja = new JSONArray();
ja.put(dataToSend);
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
You can try:
//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
JSONObject newEntry = new JSONObject();
newEntry.put("nodeId","node3");
nodesArray.put(newEntry);
jsonResponse.put("nodes",nodesArray);
} catch (JSONException e) {
e.printStackTrace();
}
Now you can post your jsonResponse.toString() as required.
I would rather go for cleaner approach, create Object with below structure -
public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
- Serialize the json -
Response response = objectMapper.readValue(responseJson, Response.class);
- Add the new incoming node object to
response-
response.getNodes().add(New Node("{new node Value}"));
- Deserialize before post -
objectMapper.writeValueAsString(response);