I googled a lot today for this subject. But I can\'t find it, How can I add a JSONArray to a JSONObject?
Because everytime I do this I get this error: Stackoverflow<
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());
I'm starting to learn about this myself, being very new to android development and I found this video very helpful.
https://www.youtube.com/watch?v=qcotbMLjlA4
It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.
Code from the video for JSONArray to JSONObject:
JSONArray queryArray = quoteJSONObject.names();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < queryArray.length(); i++){
list.add(queryArray.getString(i));
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
Just try below a simple solution:
JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);
whenever my JSON request is like:
{
"role": "RT",
"orders": [
{
"order_id": "ORDER201908aPq9Gs",
"cart_id": 164444,
"affiliate_id": 0,
"orm_order_status": 9,
"status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
"status_date": "2020-04-15",
}
]
}
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}