写入json文件的格式不正确

时间:2015-01-27 14:45:13

标签: java json gson

我正在创建一个java项目,它将数据写入已经存在的json文件。我正在使用gson库来编写。问题是当我写json时,它写在文件的末尾而不是里面。这是我的json在我运行程序之前

{
 "trips":[
{
  "tripname":"Goa",
"members":"john"}
]
}

这是我的java代码

FileOutputStream os=new FileOutputStream(file,true);
BufferedWriter bw=new BufferedWriter(new   OutputStreamWriter(os));
Gson gson=new GsonBuilder().setPrettyPrinting().create();
String temp=gson.toJson(trips);
bw.append(temp);
bw.close();

这是我的输出json

{
 "trips":[
  {
  "tripname":"Goa",
  "members":"john"}
 ]
 }{
  "tripname": "trip1",
"members": "xyzxyz"
}

新添加的必须在trip数组中,我该如何实现它。

1 个答案:

答案 0 :(得分:-1)

问题是你没有使用Gson。您需要Java Bean使用正确的Gson注释,并使用Gson进行序列化。

请看这个例子:https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

编辑 或多或少看起来像这样:

public class Trip implements Serializable {
  private String tripName;
  private String members;

  // getters setters
}

使用Gson:

List<Trip> trips = new ArrayList<>();
// add to list

Gson gson = new Gson();    

// to json
String json = gson.toJson(trips)

// from json
Type collectionType = new TypeToken<Collection<Trip>>(){}.getType();
List<Trip> trips2 = gson.fromJson(json, collectionType);