Gson 简明教程
Gson - Null Object Support
默认情况下,Gson 会忽略 NULL 值,生成经过优化的 Json 内容。但 GsonBuilder 提供了使用 GsonBuilder.serializeNulls() 方法在 Json 输出中显示 NULL 值的标志。
Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls() method.
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.create();
Example without serializeNulls Call
在 C:\>GSON_WORKSPACE 创建一个名为 GsonTester 的 Java 类文件。
Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File - 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+ "]";
}
}
Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
现在运行 GsonTester 来查看结果 −
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
验证输出。
Verify the output.
{"rollNo": 1}
Student[ name = null, roll no: 1]
Example with serializeNulls call
在 C:\>GSON_WORKSPACE 中创建一个名为 GsonTester 的 Java 类文件。
Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File - 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+ "]";
}
}
Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
现在运行 GsonTester 以查看结果 −
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
验证输出。
Verify the output.
{
"rollNo": 1,
"name": null
}
Student[ name = null, roll no: 1]