不吹不黑,google的gson一直是我最喜欢用的json序列化反序列化类库,用起来挺方便的。
下面介绍一下GsonBuilder的两个设置,
1 excludeFieldsWithoutExposeAnnotation()
序列化时移除那些没有打上@Expose标签的属性
2 setDateFormat(String pattern)
设置序列化时日期的序列化格式
下面举个栗子~
package com.kingnet.xydb.web.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import java.util.Date;
/**
* Created by xiaoj on 2016/6/29.
*/
public class GsonTest {
public static void main(String[] args) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
GsonTest gsonTest = new GsonTest();
gsonTest.setName("xiaojun");
gsonTest.setAge(30);
gsonTest.setDate(new Date());
String json = gson.toJson(gsonTest);
System.out.println(json); //输出: {"name":"xiaojun","date":"2016-06-29 19:54:28"}
GsonTest gsonTest1 = gson.fromJson(json,GsonTest.class);
System.out.println(gsonTest1);// 输出:GsonTest{name='xiaojun', age=0, date=Wed Jun 29 19:54:28 CST 2016}
}
@Expose
private String name;
private int age;
@Expose
private Date date;
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 Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "GsonTest{" +
"name='" + name + '\'' +
", age=" + age +
", date=" + date +
'}';
}
}