Android 如何创建格式正确的gson对象数组

Android 如何创建格式正确的gson对象数组,android,json,file-io,gson,Android,Json,File Io,Gson,每次有人在我的应用程序中进行交易时,我都希望使用json/gson将其保存到本地存储。我相信我就快到了,但我的问题是每次写入json文件时都要正确格式化它 我希望在每次创建事务对象时都附加到文件中,然后在某个时刻从文件中读取每个事务对象以显示在列表中。以下是我到目前为止的情况: public void saveTransaction(Transaction transaction) throws JSONException, IOException {

每次有人在我的应用程序中进行交易时,我都希望使用json/gson将其保存到本地存储。我相信我就快到了,但我的问题是每次写入json文件时都要正确格式化它

我希望在每次创建事务对象时都附加到文件中,然后在某个时刻从文件中读取每个事务对象以显示在列表中。以下是我到目前为止的情况:

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();
        }
    }
我的transaction对象有一个amount、一个user id和一个boolean,使用此代码我可以读取以下json字符串:

{"mAmount":"12.34","mIsAdd":"true","mUID":"76163164"}
{"mAmount":"56.78","mIsAdd":"true","mUID":"76163164"}
我这样读取这些值,但只能读取第一个值(我猜是因为它们不在数组/格式正确的json对象中):

public ArrayList loadTransactions()抛出IOException、jsoneexception{
ArrayList allTransactions=新建ArrayList();
BufferedReader reader=null;
试一试{
//打开文件并将其读入字符串生成器
InputStream in=mContext.openFileInput(mFilename);
reader=新的BufferedReader(新的InputStreamReader(in));
StringBuilder jsonString=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
//换行符被省略且不相关
jsonString.append(第行);
}
//在此从jsonString中提取每个事务-----
}catch(filenotfounde异常){
//忽略这一点,在第一次启动时发生
}最后{
if(读卡器!=null)
reader.close();
}
返回所有交易;
}

我不确定我是否理解您的问题,但是您是否尝试过创建一个TransactionCollection对象,该对象具有
ArrayList transactions

从TransactionCollection对象而不是每个事务创建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;
    }