T - the type of objects this Serializer can serialize.public interface Serializer<T>
ObjectWriter. Genson Serializers work like classic
serializers from other libraries. Here is an example of a custom serializer that will delegate
the serialization of Author type to the library:
class Book {
String title;
int totalPages;
Author author;
}
class Author {
String name;
}
static class BookSerializer implements Serializer<Book> {
private final Serializer<Author> authorSerializer;
// a reference to a delegated author serializer
BookSerializer(Serializer<Author> authorSerializer) {
this.authorSerializer = authorSerializer;
}
public void serialize(Book book, ObjectWriter writer, Context ctx) {
// we don't have to worry if book is null by default it is handled by the library.
writer.beginObject().writeName("title").writeValue(book.title).writeName("totalPages")
.writeValue(book.totalPages).writeName("author");
// again no need to check if author is null the library will handle it
authorSerializer.serialize(book.author, writer, ctx);
writer.endObject();
}
public final static Factory<Serializer<Book>> bookFactory = new Factory<Serializer<Book>>() {
public Serializer<Book> create(Type type, Genson genson) {
Serializer<Author> authorSerializer = genson.provideConverter(Author.class);
return new GoodBookSerializer(authorSerializer);
}
}
}
As you see it involves very few lines of code and is quite powerful.| Modifier and Type | Method and Description |
|---|---|
void |
serialize(T object,
ObjectWriter writer,
Context ctx) |
void serialize(T object, ObjectWriter writer, Context ctx) throws Exception
object - we want to serialize. The object is of type T or a subclass (if this serializer
has been registered for subclasses).writer - to use to write data to the output stream.ctx - the current context.JsonBindingExceptionJsonStreamExceptionExceptionCopyright © 2019. All rights reserved.