gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:47:51 24 4
gpt4 key购买 nike

我正在尝试将数据插入多个 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);

但我想动态创建这些 JSONObject,因为我不知道在编码时需要多少它们,以及在那些动态创建的 JSONObject 中> 数据将从productidqtylistprice三个ArrayList中填充。

很明显,那些动态创建的 JSONObject 的数量将取决于任何一个 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);

}

最后所有的 JSONObjects 都在 myJSONObjects 中。

关于java - 如何动态创建多个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25358485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com