Gson-空对象支持
默认情况下,Gson会生成优化后的Json内容,而忽略NULL值。但是GsonBuilder提供了使用GsonBuilder.serializeNulls() 方法在Json输出中显示NULL值的标志。
1 没有使用serializeNulls方法
1.1 编写核心类
MainApp:
package com.yiidian.gson;
import com.google.gson.Gson;
/**
* 一点教程网 - http://www.yiidian.com
*/
public class MainApp {
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+ "]";
}
}
1.2 运行测试
2 使用了serializeNulls方法
2.1 编写核心类
MainApp:
package com.yiidian.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* 一点教程网 - http://www.yiidian.com
*/
public class MainApp {
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+ "]";
}
}
2.2 运行测试
热门文章
优秀文章