I am trying to insert data into multiple JSON objects but I don't know how to create them dynamically in android.
In the hard coded way it is something like:-
JSONArray pdoInformation = new JSONArray();
JSONObject pDetail1 = new JSONObject();
JSONObject pDetail2 = new JSONObject();
JSONObject pDetail3 = new JSONObject();
pDetail1.put("productid", 1);
pDetail1.put("qty", 3);
pDetail1.put("listprice", 9500);
pDetail2.put("productid", 2);
pDetail2.put("qty", 4);
pDetail2.put("listprice", 8500);
pDetail3.put("productid", 3);
pDetail3.put("qty", 2);
pDetail3.put("listprice", 1500);
pdoInformation.put(pDetail1);
pdoInformation.put(pDetail2);
pdoInformation.put(pDetail3);
But I want to create these JSONObject dynamically as I don't know how many of them are going to be needed while coding and in those dynamically created JSONObject the data will be filled from three ArrayList of productid, qty and listprice.
So its obvious that the number of those dynamically created JSONObject will depend on the size of any one ArrayList.
ArrayList :-
ArrayList<String> productid = new ArrayList<String>();
ArrayList<String> qty = new ArrayList<String>();
ArrayList<String> listprice= new ArrayList<String>();
List<JSONObject> myJSONObjects = new ArrayList<JSONObject> (productid.size());
for(int i=0; i<productid.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productid.get(i) );
obj.put("qty", qty.get(i));
obj.put("listprice", listprice.get(i));
myJSONObjects.add(obj);
}
at the end all JSONObjects are in myJSONObjects.
I want to create these JSONObject dynamically as I don't know how many of them are going to be needed while coding.
As you are already having ArrayList, iterate through it and create a new JSONObject in each iteration and put it inside ArrayList<JSONObject>.
For example: JSONObject objJSON;
for(int i=0; i<numberOfItems; i++) {
objJSON = new JSONObject();
objJSON.put("productid", 1);
objJSON.put("qty", 3);
objJSON.put("listprice", 9500);
pdoInformation.put(objJSON);
}
The data will be filled from three ArrayList of productid, qty and listprice
You shouldn't take different ArrayLists because you have to manage each lists as many as you have, instead of that create a single ArrayList of type user defined class. For example, ArrayList<Product> where Product type would contain setter/getter methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With