Android内部存储,如何正确解析JSON文本文件

Chr*_*ris 6 android json

我正在创建一个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();
}
Run Code Online (Sandbox Code Playgroud)

现在我得到一个看起来像这样的文本文件:

{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}, 
Run Code Online (Sandbox Code Playgroud)

我现在想在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";
}
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误.我从一个很棒的教程中获得了解析代码:http://www.ibm.com/developerworks/web/library/x-andbene1/? ca = dr-#author1在这个例子中,代码期望括号围绕整个文件,最后一个对象后没有逗号.所以我需要:

[{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}]
Run Code Online (Sandbox Code Playgroud)

但是我在代码中一次编写了一些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"
     }
]
Run Code Online (Sandbox Code Playgroud)

如何读取第一个数组,添加第二个数据然后重新编写文件,两个数组合并为一个?

Ben*_*tin 3

您需要使用JSONArray来创建一个JSON objects. 一旦执行了 toString(),您将获得预期的括号。您也不需要手动添加逗号。

查看http://developer.android.com/reference/org/json/JSONArray.html了解更多信息