我的json文件如下:
[
{
"title": "hardik2",
"note": "new note created",
"date": "current date"
},
{
"title": "hardik2",
"note": "2 new note",
"date": "2 current date"
},
......I want to add same object here like previous one
]
我想在同一数组中添加更多对象而不丢失前一个对象 怎么做?
我目前正在做的是
FileOutputStream outputStream=openFileOutput("note.json",MODE_APPEND);
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("title",title.getText().toString());
jsonObject.put("date","current date");
jsonObject.put("note",note.getText().toString());
jsonArray.put(jsonObject);
outputStream.write(jsonObject.toString().getBytes());
答案 0 :(得分:0)
这是使用Gson的简单方法。
Gson解决方案
第一个make类,具有三个变量title,note和date。
class DataOfJson {
private String title;
private String note;
private String date;
public DataOfJson(String title, String note, String date){
this.title=title;
this.note=note;
this.date=date;
}
}
在列表中添加项目
FileOutputStream outputStream=openFileOutput("note.json",MODE_APPEND);
String data= getStringFromFile("path/note.json");
Type listType = new TypeToken<List<DataOfJson>>() {}.getType();
List<DataOfJson> yourList = new Gson().fromJson(data,listType);
yourList.add( new DataOfJson(title.getText().toStri g(),note.getText().toString(),"current date");
outputStream.write(new Gson().toJson(yourList));
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}