private void saveJson(JsonBean bean) {
File file = new File(getFilesDir(), "json.txt");
BufferedReader br = null;
String json;
try {
br = new BufferedReader(new FileReader(file));
json = br.readLine();
} catch (Exception e) {
e.printStackTrace();
json = "";
}
Gson gson = new Gson();
ArrayList<ProductDetailBean> productList = new ArrayList<>();
if (!"".equals(json)) {
Type type = new TypeToken<ArrayList<ProductDetailBean>>(){}.getType();
productList = gson.fromJson(json, type);
}
int index = -1;
for (int i = 0; i < productList.size(); i++) {
ProductDetailBean productDetailBean = productList.get(i);
int id = productDetailBean.product.id;
if (id == bean.product.id) {
index = i;
break;
}
}
if (index != -1) {
productList.remove(index);
}
productList.add(bean);
String newJson = gson.toJson(productList);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(newJson.getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取本地json数据如下:
ArrayList<JsonBean> jsonList = new ArrayList<>();
private void geJson() {
File file = new File(getFilesDir(), "json.txt");
BufferedReader br = null;
String json;
try {
br = new BufferedReader(new FileReader(file));
json = br.readLine();
} catch (Exception e) {
e.printStackTrace();
json = "";
}
Gson gson = new Gson(); if (!"".equals(json)) {
Type type = new TypeToken<ArrayList<JsonBean>>() {
}.getType();
jsonList = gson.fromJson(json, type);
Collections.reverse(jsonList);
mAdapter = new MyAdapter();
lvList.setAdapter(mAdapter);
} if (br != null) {
try {
br.close(); } catch (IOException e) {
e.printStackTrace();
}
} }