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

时间:2014-07-07 17:24:00

标签: android json file-io gson

每当有人在我的应用程序中进行交易时,我想使用json / gson将其保存到本地存储。我相信我几乎在那里,但我的问题是每次写入时都正确格式化json文件。

我想在每次创建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;
    }

1 个答案:

答案 0 :(得分:0)

我不确定我理解您的问题,但您是否尝试过创建一个具有ArrayList<Transaction> transactions

的TransactionCollection对象

从TransactionCollection对象而不是每个事务创建你的json?