【发布时间】: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;
}
【问题讨论】: