构建JSONArray

时间:2014-07-09 14:09:36

标签: java json

我认为在这种情况下,一段代码比成千上万的解释更好:

我的代码:

ArrayList<String[]> req = new ArrayList<String[]>(DAO.getInstance().dropList(request.getParameter("rname")));
JSONObject j = new JSONObject();
JSONArray m = new JSONArray();
for(String[] s : req){
    try{
        j.put("id",s[0]);
        j.put("name",s[1]);
        m.put(j);
        System.out.println("id and name from DAO : " + s[0] + " " + s[1]);
        System.out.println("JSON object : " + j);
        System.out.println("JSON array : " + m);
    }catch (Exception e){}
}

控制台:

id and name from DAO : 1 Bob Sinclar
JSON object : {"id":"1","name":"Bob Sinclar"}
JSON array : [{"id":"1","name":"Bob Sinclar"}]
id and name from DAO : 2 Kurt Cobain
JSON object : {"id":"2","name":"Kurt Cobain"}
JSON array : [{"id":"2","name":"Kurt Cobain"},{"id":"2","name":"Kurt Cobain"}]
id and name from DAO : 3 AAA AAcc
JSON object : {"id":"3","name":"AAA AAcc"}
JSON array : [{"id":"3","name":"AAA AAcc"},{"id":"3","name":"AAA AAcc"},{"id":"3","name":"AAA AAcc"}]
id and name from DAO : 4 Bruce Wayne
JSON object : {"id":"4","name":"Bruce Wayne"}
JSON array : [{"id":"4","name":"Bruce Wayne"},{"id":"4","name":"Bruce Wayne"},{"id":"4","name":"Bruce Wayne"},{"id":"4","name":"Bruce Wayne"}]
id and name from DAO : 5 Tyler Dordon
JSON object : {"id":"5","name":"Tyler Dordon"}
JSON array : [{"id":"5","name":"Tyler Dordon"},{"id":"5","name":"Tyler Dordon"},{"id":"5","name":"Tyler Dordon"},{"id":"5","name":"Tyler Dordon"},{"id":"5","name":"Tyler Dordon"}]

正如你所看到的,不是添加一个新元素,而是用最后一个条目替换所有元素,就像我添加一个指向我的JSONObject的指针而不是它的内容......

任何想法的人?

1 个答案:

答案 0 :(得分:1)

在循环中初始化您的JSONObject

for(String[] s : req){
    try{
        JSONObject j = new JSONObject();
         ...

...否则您将更新对JSONObject的引用并再次将其添加到JSONArray,从而添加相同JSONObject的多个副本。

在序列化JSONObjectJSONArray之前,它们的行为与普通的Java Object相似,只要对同一个引用调用的方法的更改应用于同一个实例。

因此,在序列化后,您将获得JSONObject中上次更新的JSONArray的多个副本。