【问题标题】:Android Internal Storage, how to properly parse a JSON text fileAndroid内部存储,如何正确解析JSON文本文件
【发布时间】: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"
     }
]

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

【问题讨论】:

    标签: android json


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      1. 要使其成为有效的 JSON 数组,您需要将 JSON 对象 ({...}) 封装在大括号 ([]) 中。因此,您可以在创建时将[ 放入文件中

        • 要么在数组完成的地方有一个点,你只需写一个右大括号] 而不是下一个逗号 (,),或者
        • 你没有这样的一个点。每当您编写下一个对象时,您都可以通过f.ex. 回到流中的一个字节

          try {
              FileChannel ch = fos.getChannel();
              ch.position(ch.position -1);
              ch.write(", ".getBytes());
              ch.write(ByteBuffer.wrap(myJSONString.getBytes()));
              ch.write("]".getBytes());
          } finally {
              out.close();
          } 
          
      2. (关于“更新”): 只需从文件中读取整个数组,在内存中更新它(通过JSONArray.put()),然后覆盖文件。

        要覆盖,请将Context.MODE_APPEND 替换为0,如the API 中所写。

        如果你正确地创建了数组会更好。如果您在更新中获得了数组,则可以搜索 ][ 的出现,在其上拆分文件,从两个对象创建 JSON,然后合并它们(再次通过 JSONArray.put())。

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-11
        • 1970-01-01
        • 2016-04-25
        相关资源
        最近更新 更多