看一下demo
public static void main(String[] args) {
// Gson gson = new Gson();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Student student = new Student(11, "zhangsan", new Date());
Student stu1 = new Student(12, "lisi", new Date());
Student stu2 = new Student(13, "wangwu", new Date());
Student stu3 = new Student(14, "weili", new Date());
List<Student> list = new ArrayList<Student>();
list.add(student);
list.add(stu1);
list.add(stu2);
list.add(stu3);
String jsonStr = gson.toJson(student, Student.class);
System.out.println(jsonStr );
String jsonListStr = gson.toJson(list);
System.out.println(jsonListStr);
System.out.println("===================分隔符======================");
String jsonSrc = "{\"age\":11,\"name\":\"zhangsan\",\"bir\":\"2014-12-05 16:46:50\"}";
Student stu = gson.fromJson(jsonSrc, Student.class);
System.out.println(stu);
List<Student> stuList = gson.fromJson(jsonListStr, new TypeToken<List<Student>>() {
}.getType());
System.out.println("========反序列化json数组==========");
System.out.println(stuList);
}
上面的是示例代码,Student是一个POJO,
public class Student {
private int age;
private String name;
@Expose(serialize = true, deserialize = false)
@SerializedName("bir")
private Date birthday;
public Student(int age, String name, Date birthday) {
this.age = age;
this.name = name;
this.birthday = birthday;
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
if (birthday == null) {
return "{\"name\":" + name + ", \"age\":" + age + "}";
} else {
return "{\"name\":" + name + ", \"age\":" + age + ", \"birthday\":" + birthday.toString() + "}";
}
}
}
说明:
1、如果是创建普通的Gson对象,可以之间使用Gson gson = new Gson(),如果需要加入自己的一些设置,可以使用GsonBuilder来创建Gson实例,例如,本实例中,希望将时间对象序列化为
yyyy-MM-dd HH:mm:ss这种格式的字符串。
2、将对象序列化为JSON对象比较简单,直接调用gson.toJson(Obj)即可。如果pojo没有作特殊设置,将序列化为默认的形式。
如果将json对象反序列化为java对象,需要设置待序列化对象的类型,例如
String jsonStr = gson.toJson(student, Student.class);
将json反序列化为普通pojo,
如果将json字符串反序列化为集合,则需要构建Type对象,例如:
List<Student> stuList = gson.fromJson(jsonListStr, new TypeToken<List<Student>>() {
}.getType());
这里是一个泛型,new TypeToken<T>(){ }.getType() ,T为待序列化为的类型。比如这里,反序列化之后的类型为集合。