2014-07-07 97 views
-1

每次有人在我的應用程序中進行事務處理時,我想使用json/gson將其保存到本地存儲中。我相信我快到了,但是我的問題是每次寫入時都正確格式化json文件。如何創建格式正確的gson對象數組

我想每次創建一個Transaction對象時追加到文件中,然後在某個時刻從文件中讀取每個Transaction對象以便在列表中顯示。以下是我迄今爲止:

public void saveTransaction(Transaction transaction) 
      throws JSONException, IOException { 

     Gson gson = new Gson(); 
     String json = gson.toJson(transaction); 

     //Write the file to disk 
     Writer writer = null; 
     try { 
      OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND); 
      writer = new OutputStreamWriter(out); 
      writer.write(json); 
     } finally { 
      if (writer != null) 
       writer.close(); 
     } 
    } 

我的交易對象有一個量,一個用戶ID和一個布爾值,與此代碼我可以閱讀以下JSON字符串寫入:

{"mAmount":"12.34","mIsAdd":"true","mUID":"76163164"} 
{"mAmount":"56.78","mIsAdd":"true","mUID":"76163164"} 

我讀取這些值,像這樣,但只能讀取第一個(我猜是因爲他們不是在一個陣列/格式正確的JSON對象):

public ArrayList<Transaction> loadTransactions() throws IOException, JSONException { 

     ArrayList<Transaction> allTransactions = new ArrayList<Transaction>(); 
     BufferedReader reader = null; 
     try { 
      //Open and read the file into a string builder 
      InputStream in = mContext.openFileInput(mFilename); 
      reader = new BufferedReader(new InputStreamReader(in)); 
      StringBuilder jsonString = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       //Line breaks are omitted and irrelevant 
       jsonString.append(line); 
      } 

      //Extract every Transaction from the jsonString here ----- 

     } catch (FileNotFoundException e) { 
      //Ignore this one, happens when launching for the first time 
     } finally { 
      if (reader != null) 
       reader.close(); 
     } 
     return allTransactions; 
    } 

回答

0

林不知道我理解你的問題,但你嘗試過ç重新創建一個TransactionCollection對象,該對象的ArrayList<Transaction> transactions

並從TransactionCollection對象而不是每個事務創建您的json?