【问题标题】:How to create a properly formatted array of gson objects如何创建格式正确的 gson 对象数组
【发布时间】:2014-07-07 17:24:00
【问题描述】:

每当有人在我的应用程序中进行交易时,我都想使用 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;
    }

【问题讨论】:

    标签: android json file-io gson


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多