Gson空對象支持
Gson默認生成優化的Json內容,忽略NULL
值。 但是GsonBuilder
提供的標誌使用GsonBuilder.serializeNulls()
方法在Json輸出中顯示NULL
值。
參考以下代碼實現 -
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.create();
不帶serializeNulls的示例調用
創建一個名爲GsonTester
的Java類文件:GsonTester.java -
import com.google.gson.Gson;
public class GsonTester {
public static void main(String args[]) {
Gson gson = new Gson();
Student student = new Student();
student.setRollNo(1);
String jsonString = gson.toJson(student);
System.out.println(jsonString);
student = gson.fromJson(jsonString, Student.class);
System.out.println(student);
}
}
class Student {
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Student[ name = "+name+", roll no: "+rollNo+ "]";
}
}
執行上面示例代碼,得到以下結果 -
{"rollNo": 1}
Student[ name = null, roll no: 1]
使用serializeNulls調用的示例
創建一個名爲GsonTester
的Java類文件:GsonTester.java -
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonTester {
public static void main(String args[]) {
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
builder.setPrettyPrinting();
Gson gson = builder.create();
Student student = new Student();
student.setRollNo(1);
String jsonString = gson.toJson(student);
System.out.println(jsonString);
student = gson.fromJson(jsonString, Student.class);
System.out.println(student);
}
}
class Student {
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Student[ name = "+name+", roll no: "+rollNo+ "]";
}
}
執行上面示例代碼,得到以下結果 -
{
"rollNo": 1,
"name": null
}
Student[ name = null, roll no: 1]