我使用simple-json
我正在尝试为jqgrid创建JSON对象。数据被添加但正确但第二条记录被覆盖。
ArrayList resList = connect.statement_query(sql, para);
jsonObject = new JSONObject();
jsonObject.put("total", resList.size()/para.length);
jsonObject.put("page", 1);
jsonObject.put("records", resList.size()/para.length);
JSONArray cellArray = new JSONArray();
JSONArray cell = new JSONArray();
JSONObject cellObj = new JSONObject();
for (int i = 0; i < resList.size(); i += para.length) {
cellObj.put("id", resList.get(i));
JSONArray temp=new JSONArray();
temp.add(resList.get(i));
temp.add(resList.get(i + 1));
temp.add(resList.get(i + 2));
temp.add(resList.get(i + 3));
temp.add(resList.get(i + 4));
cell=temp;
cellObj.put("cell", cell);
System.out.println("Cell Obj: "+cellObj.toJSONString());
cellArray.add(cellObj);
System.out.println("Cell Array: "+cellArray.toJSONString());
//cellObj.clear();
temp.clear();
}
System.out.println("Cell Array-Out: "+cellArray);
jsonObject.put("rows", cellArray);
结果如下:
Cell Obj: {"id":"1000","cell":["1000","BE6K","vshekhar","2014-06-02","N\/A"]}
Cell Array: [{"id":"1000","cell":["1000","BE6K","vshekhar","2014-06-02","N\/A"]}]
Cell Obj: {"id":"1001","cell":["1001","BOA","maahamad","2013-05-01","N\/A"]}
Cell Array: [{"id":"1001","cell":["1001","BOA","maahamad","2013-05-01","N\/A"]},{"id":"1001","cell":["1001","BOA","maahamad","2013-05-01","N\/A"]}]
Cell Array-Out: [{"id":"1001","cell":[]},{"id":"1001","cell":[]}]
答案 0 :(得分:0)
1)对象重写 -
您需要将cellObj重新信号化为for循环。
for(int i = 0; i&lt; resList.size(); i + = para.length){
cellObj = new JSONObject();
2)让细胞空白 -
你正在通过'temp.clear();'清除临时Cell对象引用temp,temp被清除,这就是获取空白数据的原因。
你可以删除temp.clear()代码。