Skip to content
This repository has been archived by the owner on Mar 15, 2022. It is now read-only.

ReaderWriter

Harald Pehl edited this page Oct 29, 2012 · 3 revisions

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:

  1. JsonReader<T>: To map from JSON to POJO
  2. JsonWriter<T>: To serialize POJOs to JSON
  3. XmlReader<T>: To map from XML to POJO
  4. XmlWriter<T>: To serialize POJOs to XML

Classic Setup

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;
    ...
}    

GIN Setup

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.

Generated Code

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.

Clone this wiki locally