【发布时间】:2010-12-12 01:43:42
【问题描述】:
我正在创建一个 Android 应用程序,该应用程序创建一个包含 JSON 对象的文本文件并将其写入内部存储。我有以下代码可以做到这一点:
JSONObject myJSON = new JSONObject();
//Set the JSON object with website, length and Id (time-stamp)
try {
myJSON.put("Length", trim)
.put("Website", data)
.put("Id", tx);
} catch (JSONException e1) {
e1.printStackTrace();
}
//Convert JSON object to a string and add a comma
String myJSONString = myJSON.toString();
myJSONString += ", ";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(myJSONString.getBytes());
fos.close();
//Log.d(TAG, "Written to file");
} catch (Exception e) {
Log.d(TAG, "cought");
e.printStackTrace();
}
现在我得到一个如下所示的文本文件:
{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10},
我现在想在 JSON 文件中收集该数据。应用程序需要编写、存储和检索 JSON。问题是当我使用以下方法解析文件中的 JSON 对象时:
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.pwh);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Id:" + post.getString("Id") + "\n";
x += "Length:" + post.getString("Length") + "\n\n";
}
它会抛出一个错误。我从一个很棒的教程中获得了解析代码:http://www.ibm.com/developerworks/web/library/x-andbene1/?ca=drs-#author1 在该示例中,代码期望整个文件周围有括号,并且在最后一个对象之后没有逗号。所以我需要:
[{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}]
但我在我的代码中一次编写了这些 JSON 行;如何操作 JSON 文本文件以获取预期格式?
更新:
问题仍然是,如果用户将 JSON 数组写入文件,然后返回并再次更改它,您会在该文件中获得 两个 JSON 数组。像这样:
[
{
"phonenumber": "15555215554",
"time": "20110113T173835",
"username": "edit username",
"email": " edit email",
"password": "edit password"
}
][
{
"phonenumber": "15555215554",
"time": "20110113T173900",
"username": "edit username",
"email": " edit email",
"password": "edit password"
},
{
"phonenumber": "15555215554",
"time": "20110113T173900",
"username": "edit username",
"email": " edit email",
"password": "edit password"
}
]
如何读取第一个数组,添加第二个数组,然后将两个数组合并为一个重新写入文件?
【问题讨论】: