-
Notifications
You must be signed in to change notification settings - Fork 16
ReaderWriter
Readers and writers are one of the basic building blocks. They are used to read / write a sinlge POJO or a list of POJOs from / to JSON or XML. Therefore Piriti knows four interfaces:
-
JsonReader<T>
: To map from JSON to POJO -
JsonWriter<T>
: To serialize POJOs to JSON -
XmlReader<T>
: To map from XML to POJO -
XmlWriter<T>
: To serialize POJOs to XML
Typically you define your readers and writer as nested interfaces (if you're familiar with UiBinder this shouldn't be a big challenge)
public class Book
{
public interface BookJsonReader extends JsonReader<Book> {}
public static final BookJsonReader JSON_READER = GWT.create(BookJsonReader.class);
public interface BookJsonWriter extends JsonWriter<Book> {}
public static final BookJsonWriter JSON_WRITER = GWT.create(BookJsonWriter.class);
public interface BookXmlReader extends XmlReader<Book> {}
public static final BookXmlReader XML_READER = GWT.create(BookXmlReader.class);
public interface BookXmlWriter extends XmlWriter<Book> {}
public static final BookXmlWriter XML_WRITER = GWT.create(BookXmlWriter.class);
String isbn;
String title;
...
}
In case you use GIN, I recommend to let GIN create and inject the reader / writer implementations:
public class Book
{
String isbn;
String title;
...
}
public interface BookJsonReader extends JsonReader<Book>
{
}
public class BookstoreModule extends AbstractModule
{
@Override
protected void configure()
{
bind(BookJsonReader.class).asEagerSingleton();
...
}
}
public class ReadBookAction
{
private final BookJsonReader reader;
@Inject
public ReadBookAction(BookJsonReader reader)
{
this.reader = reader;
}
...
}
Please make sure you bind the reader and writer implementations as eager singeltons. Otherwise References between POJOs might not get (de)serialized.
In any case a reader / writer implementations are generated for you. By default all fields in the specified POJO and its superclasses are (de)serialized to/from JSON/XML. See Annotations and Supported Types for more details.