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的数据将来自三个被填充ArrayList的productid,qty和listprice.
很明显,动态创建的数量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)
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中.
| 归档时间: |
|
| 查看次数: |
6435 次 |
| 最近记录: |