标签:
示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。import com.google.gson.Gson;
import java.util.Calendar;
public class StudentToJson {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(2000, 1, 1, 0, 0, 0);
Student student = new Student("Duke", "Menlo Park", dob.getTime());
Gson gson = new Gson();
String json = gson.toJson(student);
System.out.println("json = " + json);
}
}
import java.util.Date;
public class Student {
private String name;
private String address;
private Date dateOfBirth;
public Student() {
}
public Student(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
以下是输出结果:
json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
标签:
原文地址:http://www.cnblogs.com/lm52111/p/5070697.html