继续使用反序列化中提到的例子。
考虑把如下Java Bean
public class Book {
private String[] authors;
private String isbn10;
private String isbn13;
private String title;
// Methods removed for brevity
}
序列化成Json
{
"title": "Java Puzzlers: Traps, Pitfalls, and Corner Cases",
"isbn-10": "032133678X",
"isbn-13": "978-0321336781",
"authors": [
"Joshua Bloch",
"Neal Gafter"
]
}
在不使用注解的情况下,Java bean当中的isbn10
和isbn13
是无法序列化成Json中的isbn-10
和isbn-13
的。我们可以通过自定义Json序列化器来实现这一转换。
public class BookSerialiser implements JsonSerializer{
public JsonElement serialize(final Book book, final Type typeOfT,
JsonSerializationContext context){
//这样就把java bean中的字段对应到Json中的字段了
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("title", book.getTitle());
jsonObject.addProperty("isbn-10", book.getIsbn10());
jsonObject.addProperty("isbn-13", book.getIsbn13());
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;
}
}
同理,在使用我们自定义的序列化器之前,我们也要向Gson注册我们的序列化器,
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookSerialiser());
那接下来我们考虑对象的嵌套,如下
{
"title": "Java Puzzlers: Traps, Pitfalls, and Corner Cases",
"isbn": "032133678X",
"authors": [
{
"id": 1,
"name": "Joshua Bloch"
},
{
"id": 2,
"name": "Neal Gafter"
}
]
}
首先定义我们的Author bean:
public class Author {
private int id;
private String name;
// Methods removed for brevity
}
修改我们的Book bean
public class Book {
private Author[] authors;
private String isbn;
private String title;
// Methods removed for brevity
}
和反序列化一样,我们修改BookSerialiser来使用JsonSerializationContext实现对于Author的序列化
public class BookSerialiser implements JsonSerializer {
@Override
public JsonElement serialize(final Book book, final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("title", book.getTitle());
jsonObject.addProperty("isbn", book.getIsbn());
//使用context来序列化Author
final JsonElement jsonAuthros = context.serialize(book.getAuthors());
//把结果加入jsonObject
jsonObject.add("authors", jsonAuthros);
return jsonObject;
}
}
这个和反序列化很类似,如果大家读过反序列化那篇文章,应该很容易理解这个。