publicclassPointAdapterextendsTypeAdapter<Point> { public Point read(JsonReader reader)throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); returnnull; } String xy = reader.nextString(); String[] parts = xy.split(","); int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); returnnew Point(x, y); } publicvoidwrite(JsonWriter writer, Point value)throws IOException { if (value == null) { writer.nullValue(); return; } String xy = value.getX() + "," + value.getY(); writer.value(xy); } }
GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Point.class, new PointAdapter()); // if PointAdapter didn't check for nulls in its read/write methods, you should instead use // builder.registerTypeAdapter(Point.class, new PointAdapter().nullSafe()); ... Gson gson = builder.create();
注解关键字
包含五个注解关键字,代码路径: com.google.gson.annotations
@Expose
@Expose 注解只有在如下构造方法初始化时才生效: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() 生效时被注解的成员变量才会参与序列化/反序列化,其他不会参与。如果不是使用该构造方法,没有任何功能。
@JsonAdapter(UserJsonAdapter.class) publicclassUser{ publicfinal String firstName, lastName; privateUser(String firstName, String lastName){ this.firstName = firstName; this.lastName = lastName; } } publicclassUserJsonAdapterextendsTypeAdapter<User> { @Overridepublicvoidwrite(JsonWriter out, User user)throws IOException { // implement write: combine firstName and lastName into name out.beginObject(); out.name("name"); out.value(user.firstName + " " + user.lastName); out.endObject(); // implement the write method } @Overridepublic User read(JsonReader in)throws IOException { // implement read: split name into firstName and lastName in.beginObject(); in.nextName(); String[] nameParts = in.nextString().split(" "); in.endObject(); returnnew User(nameParts[0], nameParts[1]); } }
特殊关键字 transient
如果被关键字 transient 申明了的字段,不会参与 Gson 的序列化和反序列化: transient int val;
使用流程
常见问题
Gson 转换过程中的空字段
如果元素看起来是个 list,但是实际一直为空,可以直接注释掉这个字段,也就是javabean 中不需要定义 comments 字段。否则会因空报错: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10796 path $.data.data[3].comments[0]