如何动态创建多个JSON对象?

Ami*_*and 1 java android json dynamic

我试图将数据插入到多个JSON对象中,但我不知道如何在android中动态创建它们.

在硬编码的方式,它是这样的: -

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);
Run Code Online (Sandbox Code Playgroud)

但我要创建这些JSONObject动态的,因为我不知道有多少人会在编码被需要,并在这些动态创建 JSONObject的数据将来自三个被填充ArrayListproductid,qtylistprice.

很明显,动态创建的数量JSONObject将取决于size任何一个ArrayList.

ArrayList : -

ArrayList<String> productid = new ArrayList<String>();
ArrayList<String> qty = new ArrayList<String>();
ArrayList<String> listprice= new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

mml*_*loo 8

 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);

}
Run Code Online (Sandbox Code Playgroud)

最后,所有JSONObject都在myJSONObjects中.