簡體   English   中英

Android內部存儲,如何正確解析JSON文本文件

[英]Android Internal Storage, how to properly parse a JSON text file

我正在創建一個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 = dr-#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"
     }
]

如何讀取第一個數組,添加第二個數據然后重新編寫文件,兩個數組合並為一個?

您需要使用JSONArray來創建JSON objects的數組。 一旦你執行了toString(),你將擁有預期的括號。 您也不需要手動添加逗號。

有關詳細信息,請查看http://developer.android.com/reference/org/json/JSONArray.html

  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. (關於“UPDATE”):只需從文件中讀取整個數組,在內存中更新它(通過JSONArray.put() ),然后覆蓋該文件。

    要覆蓋,請將Context.MODE_APPEND替換為0,如API所述

    如果正確創建數組會更好。 如果您在更新中獲得了數組,則可以搜索][ ,將文件拆分為該文件,從兩個對象創建JSON,然后合並它們(再次通過JSONArray.put() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM