我正在使用此代码:
JSONObject jO = new JSONObject();
try {
jO.put("item1", true);
jO.put("item2", value2);
jO.put("item3", value3);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String json = null;
try {
json = jO.toString(4);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File jsonFile = new File(nContext.getDir("json", 0), "dashboard.json");
//simple utility method to write the json file
Utils.writeToFile(jsonFile, json);
得到这个结果:
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
在同一段代码的下一次运行中,我希望实现的目标是:
{
"pass1": {
"item3": "12345",
"item2": "abcde",
"item1": true
},
"pass2": {
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
}
或许这可能更好吗?
{
"pass1": [
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
],
"pass2": [
{
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
]
}
我知道这意味着代码中的更改包含“嵌套”对象/数组。
哪一个更好,考虑到我将解析JSON以构建ListView
?
有什么想法吗?
答案 0 :(得分:2)
我找到了解决方案,感谢其他用户的评论以及“已退休”的答案,此处不再出现。也许是我的错不清楚。
public void addEntryToJsonFile(Context ctx, String id, String name, String size) {
// parse existing/init new JSON
File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
String previousJson = null;
if (jsonFile.exists()) {
try {
previousJson = Utils.readFromFile(jsonFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
previousJson = "{}";
}
// create new "complex" object
JSONObject mO = null;
JSONObject jO = new JSONObject();
try {
mO = new JSONObject(previousJson);
jO.put("completed", true);
jO.put("name", name);
jO.put("size", size);
mO.put(id, jO); //thanks "retired" answer
} catch (JSONException e) {
e.printStackTrace();
}
// generate string from the object
String jsonString = null;
try {
jsonString = mO.toString(4);
} catch (JSONException e) {
e.printStackTrace();
}
// write back JSON file
Utils.writeToFile(jsonFile, jsonString);
}
答案 1 :(得分:1)
:
oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
root = oldJson
} else {
root = new JSONObject()
root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)