使用gson序列化时空json文件



我想将Student对象序列化为Student。json文件,在我的代码中是student。

主要思想是我创建一个json字符串,从它创建一个学生,然后再次从学生对象创建一个json字符串,最后将学生对象序列化到一个json文件。

下面是我的代码:
import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.Writer; 
import java.nio.file.Paths;
import java.io.IOException;
import java.nio.file.Files;
public class JaJson {
public static void main(String args[]) {  
System.out.println("Hello");  
String jsonString = "{"name":"Mahesh", "age":21}"; 
GsonBuilder builder = new GsonBuilder(); 
builder.setPrettyPrinting(); 
Gson gson = builder.create(); 
Student student = gson.fromJson(jsonString, Student.class);
System.out.println("student object");    
System.out.println(student);    
jsonString = gson.toJson(student);
System.out.println("student string");  
System.out.println(jsonString); 
String sFileName = "student.json";
try{
//Writer writer = Files.newBufferedWriter(Paths.get(sFileName));
//gson.toJson(student, writer);
Writer writer = new FileWriter(sFileName);
gson.toJson(student, writer);
} catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}  
public JaJson(){
System.out.println("what time is it ?");
}
}

这里是Student.java

public class Student { 
private String name; 
private int age; 
public Student(){} 

public String getName() { 
return name; 
}

public void setName(String name) { 
this.name = name; 
} 

public int getAge() { 
return age; 
}

public void setAge(int age) { 
this.age = age; 
}

public String toString() { 
return "Student [ name: "+name+", age: "+ age+ " ]"; 
}  
}
下面是程序的输出:
Hello
student object
Student [ name: Mahesh, age: 21 ]
student string
{
"name": "Mahesh",
"age": 21
}

但是它产生一个空的学生。Json I don't understand…

你知道少了什么吗?

我忘了加上:

writer.flush(); //flush data to file   <---
writer.close(); //close write  

在我的代码中为:

try{
//Writer writer = Files.newBufferedWriter(Paths.get(sFileName));
//gson.toJson(student, writer);
Writer writer = new FileWriter(sFileName);
gson.toJson(student, writer);
writer.flush(); //flush data to file   <---
writer.close(); //close write  
} catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}

相关内容

  • 没有找到相关文章