我正在创建一个java程序,它使用Gson库读取和写入数据到json文件。当我将新数据写入该json文件时,它将写入文件的末尾,但不会写入json中的对象内。
这是我的json内容:
{
"employees":[
{
"name":"xxxxxxx",
"position":"yyyyyy"}
]
}
这是我的代码:
private static void writetojson(Hisab hi) {
try {
FileOutputStream os=new FileOutputStream(file,true);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
Gson gson=new GsonBuilder().setPrettyPrinting().create();
String temp=gson.toJson(hi);
bw.append(temp);
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
和DTO课程
public class Hisab {
String empname;
String position;
public String getempname() {
return empname;
}
public void setempname(String empname) {
this.empname = empname;
}
public String getposition() {
return position;
}
public void setposition(String opsition) {
this.position = position;
}
}
这是我运行程序时的输出:
{
"employees":[
{
"name":"xxxxxxx",
"position":"yyyyyy"}
]
}
{
"name":"zzzzzz",
"position":"aaaaaaa"}
但这是我想要的输出:
{
"employees":[
{
"name":"xxxxxxx",
"position":"yyyyyy"},
{
"name":"zzzzzz",
"position":"aaaaaaa"}
]
}
如何解决这个问题。请帮帮我。
答案 0 :(得分:2)
您的方法遇到了几个问题,第一个问题是如果由于某种原因附加失败,您可能会丢失原始内容和新内容。
更重要的是,您的存储格式相当奇怪;为什么单个对象键?它不需要;只是废弃它,并直接存储数组。
现在,我不做Gson而是杰克逊,所以我无法帮助你处理实际的代码,但基本上你的代码应该是这样的:
final Charset cs = StandardCharsets.UTF_8;
final Path toReplace = Paths.get("whereverisyourfile");
final Path newContents = toReplace.resolveSibling("newcontents.json");
try (
final BufferedReader reader = Files.newBufferedReader(toReplace, cs);
final BufferedWriter writer = Files.newBufferedWriter(newContents, cs,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
) {
// read old content, manipulate, write new contents
}
// IOException is THROWN, not logged
Files.move(newContents, toReplace, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
现在,关于如何阅读旧内容和写作,您有两个选择:
以上是您的选择,取决于所存储数据的大小等。
这个方法应该抛出IOException(如果有的话),以便你可以处理异常情况。只是printStackTrace()
异常绝不是一个好选择。
答案 1 :(得分:1)
创建基础类
public class Employee
{
private String name;
private String position;
// getter setter
}
public class RootObject
{
private ArrayList<Employee> employees;
// getter setter
}
Gson gson = new Gson();
RootObject rootObj = new RootObject();
rootObj.setEmployees(yourList);
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(rootObj);
答案 2 :(得分:1)
你的DTO必须是,
class JsonCollection {
ArrayList<Hisab> employees;
public JsonCollectio() {
this.employees = new ArrayList<Hisab>();
}
public void setEmployees( ArrayList<Hisab> emps ) {
this.employees = emps;
}
public ArrayList<Hisab> getEmployees() {
return this.employees;
}
public void addHisab( Hisab h ) {
this.employees.add( h );
}
}
现在,你的writeToJson方法应该是,
public void writeToJson( Hisab h ) {
// I am assuming this string has the current Json. Get this from file.
String currentJsonString = "Some Json, you got from file";
Gson gson=new GsonBuilder().setPrettyPrinting().create();
JsonCollection jsonColl = gson.fromJson( currentJsonString, JsonCollection.class );
// Add your hisab to the collection.
jsonColl.addHisab( h );
// Now write this string to file
String newJsonString =gson.toJson( jsonColl );
System.out.print( newJsonString );
}