Json轉換利器Gson之實例二-Gson注解和GsonBuilder
來源:程序員人生 發布時間:2015-04-22 08:38:52 閱讀次數:4454次
有時候我們不需要把實體的所有屬性都導出,只想把1部份屬性導出為Json.
有時候我們的實體類會隨著版本的升級而修改.
有時候我們想對輸出的json默許排好格式.
... ...
請看下面的例子吧:
實體類:
-
import java.util.Date;
-
-
import com.google.gson.annotations.Expose;
-
import com.google.gson.annotations.SerializedName;
-
-
public class Student {
-
private int id;
-
-
@Expose
-
private String name;
-
-
@Expose
-
@SerializedName("bir")
-
private Date birthDay;
-
-
public int getId() {
-
return id;
-
}
-
-
public void setId(int id) {
-
this.id = id;
-
}
-
-
public String getName() {
-
return name;
-
}
-
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
public Date getBirthDay() {
-
return birthDay;
-
}
-
-
public void setBirthDay(Date birthDay) {
-
this.birthDay = birthDay;
-
}
-
-
@Override
-
public String toString() {
-
return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
-
+ name + "]";
-
}
-
-
}
測試類:
-
import java.util.ArrayList;
-
import java.util.Date;
-
import java.util.List;
-
-
import com.google.gson.FieldNamingPolicy;
-
import com.google.gson.Gson;
-
import com.google.gson.GsonBuilder;
-
import com.google.gson.reflect.TypeToken;
-
-
public class GsonTest2 {
-
-
public static void main(String[] args) {
-
-
Gson gson = new GsonBuilder()
-
.excludeFieldsWithoutExposeAnnotation()
-
.enableComplexMapKeySerialization()
-
.serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
-
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
-
.setPrettyPrinting()
-
.setVersion(1.0)
-
-
-
.create();
-
-
-
-
Student student1 = new Student();
-
student1.setId(1);
-
student1.setName("李坤");
-
student1.setBirthDay(new Date());
-
-
-
System.out.println("----------簡單對象之間的轉化-------------");
-
-
String s1 = gson.toJson(student1);
-
System.out.println("簡單Bean轉化為Json===" + s1);
-
-
-
Student student = gson.fromJson(s1, Student.class);
-
System.out.println("Json轉為簡單Bean===" + student);
-
-
-
Student student2 = new Student();
-
student2.setId(2);
-
student2.setName("曹貴生");
-
student2.setBirthDay(new Date());
-
-
Student student3 = new Student();
-
student3.setId(3);
-
student3.setName("柳波");
-
student3.setBirthDay(new Date());
-
-
 
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
------分隔線----------------------------
------分隔線----------------------------