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

时间:2014-08-18 07:46:57

标签: 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);

但我想动态创建这些JSONObject,因为我不知道编码时需要多少{}} {}动态创建JSONObject数据将被填充来自ArrayList productidqtylistprice的三个JSONObject

很明显,动态创建size的数量取决于任何一个ArrayList的{​​{1}}。

ArrayList: -

ArrayList<String> productid = new ArrayList<String>();
ArrayList<String> qty = new ArrayList<String>();
ArrayList<String> listprice= new ArrayList<String>();

4 个答案:

答案 0 :(得分:6)

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

}

最后所有JSONObject都在myJSONObjects中。

答案 1 :(得分:2)

  

我想动态创建这些JSONObject,因为我不知道有多少   编码时将需要它们。

由于您已经拥有ArrayList,请在每次迭代中迭代并创建一个新的JSONObject并将其放在ArrayList<JSONObject>内。

例如: 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);
}
  

数据将从productid,qty和的三个ArrayList中填充   listprice

您不应该使用不同的ArrayLists,因为您必须尽可能多地管理每个列表,而不是创建一个类型为用户定义类的ArrayList。例如,ArrayList<Product>其中Product类型将包含setter / getter方法。

答案 2 :(得分:1)

在此设计中,如果将数据划分为多个Arraylists,您将如何将数据相互关联。

您似乎需要稍微重新设计数据结构。

您应该保留一个Arraylist,而不是使用三个ArrayLists。

那个Arraylist将持有豆子的对象。

对于前。

class product{
private double productid;
private double listprice;
private long qty;

// getters and setters
}

并将所有对象保存在一个Arraylist中,然后通过循环遍历它,在创建JSON时将所有三个值组合在一起。

答案 3 :(得分:0)

JSON只是一个文本字符串。你可以简单地写一下:

    String jsonString = "[";
    jsonString = jsonString  + "{\""productid\":1",\"qty\":3,\"listprice\":9500}";
    jsonString = jsonString  + "{\""productid\":2",\"qty\":4,\"listprice\":8500}";
    jsonString = jsonString  + "{\""productid\":3",\"qty\":2,\"listprice\":1500}";
...
    jsonString = jsonString  + "]";

这可能是这样做的原始方式。

我正在使用(不是在android中,但在jsp中,所以不可能)gson,它也适用于arraylist对象,所以你可以创建对象数组,之后只要求他生成json文本。 / p>