上一篇是默认的Gson对象,默认的TypeAdapter对象
这一篇,通过GsonBuilder注册TypeAdapter,可构造自定义的TypeAdapter对象
实例:
public class GsonTest {
private static String jsonStr = "{\n" +
" \"title\": \"Java Puzzlers: Traps, Pitfalls, and Corner Cases\",\n" +
" \"isbn\": \"032133678X\",\n" +
" \"authors\": [\n" +
" \"Joshua Bloch\",\n" +
" \"Neal Gafter\"\n" +
" ]\n" +
"}";
public static void main(String[] args) {
testWithGson();
// testWithSerialiser();
// testWithDeserializer();
// testWithTypeAdapter();
}
private static void testWithGson() {
Gson gson = new Gson();
//反序列化
Book book = gson.fromJson(jsonStr, Book.class);
System.out.println(book);
//序列化
String json = gson.toJson(book);
System.out.println(json);
}
private static void testWithSerialiser() {
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new BookSerialiser());
gsonBuilder.setPrettyPrinting();
final Gson gson = gsonBuilder.create();
//自定义JsonSerialiser
final Book javaPuzzlers = new Book();
javaPuzzlers.setTitle("Java Puzzlers: Traps, Pitfalls, and Corner Cases");
javaPuzzlers.setIsbn("032133678X");
javaPuzzlers.setAuthors(new String[]{"Joshua Bloch", "Neal Gafter"});
//序列化
final String json = gson.toJson(javaPuzzlers);
System.out.println(json);
}
private static void testWithDeserializer() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new BookDeserializer());
Gson gson = gsonBuilder.create();
//自定义JsonDeserialiser,反序列化
Book book = gson.fromJson(jsonStr, Book.class);
System.out.println(book);
}
private static void testWithTypeAdapter() {
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new BookTypeAdapter());
gsonBuilder.setPrettyPrinting();
final Gson gson = gsonBuilder.create();
System.out.println(gson);
//自定义TypeAdapter
final Book book = new Book();
book.setAuthors(new String[]{"Joshua Bloch", "Neal Gafter"});
book.setTitle("Java Puzzlers: Traps, Pitfalls, and Corner Cases");
book.setIsbn("978-0321336781");
//序列化
final String json = gson.toJson(book);
System.out.println("Serialised");
System.out.println(json);
//反序列化
final Book parsedBook = gson.fromJson(json, Book.class);
System.out.println("\nDeserialised");
System.out.println(parsedBook);
}
}
public class Book {
private String[] authors;
private String isbn;
private String title;
//省略get/set方法
}
public class BookSerialiser implements JsonSerializer<Book> {
@Override
public JsonElement serialize(Book book, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("title", book.getTitle());
jsonObject.addProperty("isbn-10", book.getIsbn());
final JsonArray jsonAuthorsArray = new JsonArray();
for (final String author : book.getAuthors()) {
final JsonPrimitive jsonAuthor = new JsonPrimitive(author);
jsonAuthorsArray.add(jsonAuthor);
}
jsonObject.add("authors", jsonAuthorsArray);
return jsonObject;
}
}
public class BookDeserializer implements JsonDeserializer<Book> {
@Override
public Book deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final JsonElement jsonTitle = jsonObject.get("title");
final String title = jsonTitle.getAsString();
final String isbn = jsonObject.get("isbn").getAsString();
final JsonArray jsonAuthorsArray = jsonObject.get("authors").getAsJsonArray();
final String[] authors = new String[jsonAuthorsArray.size()];
for (int i = 0; i < authors.length; i++) {
final JsonElement jsonAuthor = jsonAuthorsArray.get(i);
authors[i] = jsonAuthor.getAsString();
}
final Book book = new Book();
book.setTitle(title);
book.setIsbn(isbn);
book.setAuthors(authors);
return book;
}
}
public class BookTypeAdapter extends TypeAdapter<Book> {
@Override
public Book read(final JsonReader in) throws IOException {
final Book book = new Book();
in.beginObject();
while (in.hasNext()) {
switch (in.nextName()) {
case "isbn":
book.setIsbn(in.nextString());
break;
case "title":
book.setTitle(in.nextString());
break;
case "authors":
book.setAuthors(in.nextString().split(";"));
break;
}
}
in.endObject();
return book;
}
@Override
public void write(final JsonWriter out, final Book book) throws IOException {
out.beginObject();
out.name("isbn").value(book.getIsbn());
out.name("title").value(book.getTitle());
out.name("authors").value(Arrays.toString(book.getAuthors()));
out.endObject();
}
}
源码解析:
- GsonBuilder注册TypeAdapter
- 无论是JsonSerializer、JsonDeserializer、自定义TypeAdapter,都是往factories中添加TypeAdapterFactory
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
TypeToken<?> typeToken = TypeToken.get(type);
factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
}
if (typeAdapter instanceof TypeAdapter<?>) {
factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
}
return this;
}
JsonSerializer & JsonDeserializer
-
如果GsonBuilder注册了JsonSerializer或者JsonDeserilizer对象
-
会构建出一个SingleTypeFactory 的工厂类,用于构造TreeTypeAdapter对象
-
TreeTypeAdapter也是个代理类,内部持有serializer、deserializer、delegate,用于完成真正的序列化、反序列操作
-
对于指定了serializer或者deserializer的TreeTypeAdatpter,对应的序列化或者反序列化,就不需要懒加载delegate进行操作
-
序列化时,serializer将对象T读取为JsonElement,再转换为JsonWriter
-
反序列化时,JsonReader会先转换为JsonElement,deserializer再转换为对象T
//代理类,内部持有serializer、deserializer、delegate,用于完成真正的序列化、反序列操作
public final class TreeTypeAdapter<T> extends TypeAdapter<T> {
private final JsonSerializer<T> serializer;
private final JsonDeserializer<T> deserializer;
final Gson gson;
private final TypeToken<T> typeToken;
private final TypeAdapterFactory skipPast;
private final GsonContextImpl context = new GsonContextImpl();
/** 代理TypeAdapter,懒加载,如果指定了serializer或者deserializer,对应的序列化或者反序列化,就不需要 */
private TypeAdapter<T> delegate;
public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
//构造函数分别赋值
}
//反序列化,如果指定了deserializer,则通过deserializer来进行处理
//否则动态获取代理typeAdapter进行处理
@Override public T read(JsonReader in) throws IOException {
if (deserializer == null) {
return delegate().read(in);
}
JsonElement value = Streams.parse(in);
return deserializer.deserialize(value, typeToken.getType(), context);
}
//序列化,如果指定了serializer,则通过serializer来进行处理
//否则动态获取代理typeAdapter进行处理
@Override public void write(JsonWriter out, T value) throws IOException {
if (serializer == null) {
delegate().write(out, value);
return;
}
JsonElement tree = serializer.serialize(value, typeToken.getType(), context);
Streams.write(tree, out);
}
//在需要的情况下,动态获取代理typeAdapter对象,进行序列化、反序列化处理
private TypeAdapter<T> delegate() {
TypeAdapter<T> d = delegate;
return d != null ? d
: (delegate = gson.getDelegateAdapter(skipPast, typeToken));
}
/**
* Returns a new factory that will match each type and its raw type against
*/
public static TypeAdapterFactory newFactoryWithMatchRawType(
TypeToken<?> exactType, Object typeAdapter) {
// only bother matching raw types if exact type is a raw type
return new SingleTypeFactory(typeAdapter, exactType, matchRawType, null);
}
//工厂类,用于构建typeAdapter对象,这里返回的是TreeTypeAdapter
private static final class SingleTypeFactory implements TypeAdapterFactory {
private final JsonSerializer<?> serializer;
private final JsonDeserializer<?> deserializer;
SingleTypeFactory(Object typeAdapter, TypeToken<?> exactType, boolean matchRawType,
Class<?> hierarchyType) {
serializer = typeAdapter instanceof JsonSerializer
? (JsonSerializer<?>) typeAdapter
: null;
deserializer = typeAdapter instanceof JsonDeserializer
? (JsonDeserializer<?>) typeAdapter
: null;
}
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return new TreeTypeAdapter<T>((JsonSerializer<T>) serializer,
(JsonDeserializer<T>) deserializer, gson, type, this);
}
}
}
JsonSerializer
T对象序列化为JsonElement对象
public interface JsonSerializer<T> {
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
}
JsonDeserializer
JsonElement对象反序列化为对象T
public interface JsonDeserializer<T> {
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException;
}
自定义TypeAdapter
通过匿名内部类的方式,在构建typeAdapter的时候,直接返回自定义typeAdapter
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
return new TypeAdapterFactory() {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
}
};
}
- 序列化,T写入JsonWriter
- 反序列化,JsonReader转换为T
public abstract class TypeAdapter<T> {
public abstract void write(JsonWriter out, T value) throws IOException;
public abstract T read(JsonReader in) throws IOException;
}
TypeAdapter的工厂类
public interface TypeAdapterFactory {
<T> TypeAdapter<T> create(Gson gson, TypeToken<T> type);
}