-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;
}