将新数据附加到JSON数据

时间:2017-11-14 14:55:15

标签: android json

我对JSON有些新意,我想编写一个简单的方法,将数据附加到我的JSON而不是创建新的JSON对象。

这是我的JSON代码:

public static JSONObject jsonObj = new JSONObject();
public static String toJSON(params) {

    try {

        jsonObj.put("Timestamp", timestamp); 
        jsonObj.put("Package Name", packageName);
        jsonObj.put("Package Label", packageLabel);
        jsonObj.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj.put("Permission Group", permGroup);
        jsonObj.put("Accept or Deny", acceptDeny);

        return jsonObj.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}

然而,当我这样称呼时,

toJSON("data0", "data", "data", "data", "data", "data");
toJSON("data1", "data1", "data1", "data1", "data1", "data1");
Log.d("JSON", FileHandle.jsonObj.toString());

它只返回我最后传递的数据:

{"Timestamp":"data1","Package Name":"data1","Package Label":"data1","Permissions Requested at Once":"data1","Permission Group":"data1","Accept or Deny":"data1"}

我想要的是:

[
 {
   "Timestamp": "data0",
   "Package Name": "data",
   "Package Label": "data",
   "Permissions Requested at Once": "data",
   "Permission Group": "data",
   "Accept or Deny": "data",
 },
 {
   "Timestamp": "data1",
   "Package Name": "data1",
   "Package Label": "data1",
   "Permissions Requested at Once": "data1",
   "Permission Group": "data1",
   "Accept or Deny": "data1",
 }
]

如何实现这一目标?感谢。

1 个答案:

答案 0 :(得分:4)

使用JSONArray作为根容器而不是JSONObject

在每次通话期间,新建JSONObject并将其放入root JSONArray

然后使用

// our root JSONArray to store JSONObject 
JSONArray jsonArr = new JSONArray();

public static String toJSON(params) {
    // inner JSONObject
    JSONObject jsonObj1 = new JSONObject();         
    try {
        // Here we convert Java Object to JSON
        jsonObj1.put("Timestamp", timestamp); // Set the first name/pair
        jsonObj1.put("Package Name", packageName);
        jsonObj1.put("Package Label", packageLabel);
        jsonObj1.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj1.put("Permission Group", permGroup);
        jsonObj1.put("Accept or Deny", acceptDeny);
        jsonArr.put(jsonObj1);
        // return string form of collected data so far as jsonarray
        return jsonArr.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}