-
Notifications
You must be signed in to change notification settings - Fork 0
ExternalMappings
The previous samples all used the mapping annotations directly in the POJO. If you don't want to 'pollute' your POJOs with Piriti annotations or you don't have direct access to the POJOs source code, you can also define the mapping annotations on the reader / writer interface: public class Order { private Date date; private List items;
// getters & setters
...
}
public class OrderItem
{
private Product product;
private int amount;
// getters & setters
...
}
public class Product
{
String id;
String name;
double price;
// getters & setters
...
}
public class Readers
{
@Mappings({
@Mapping(value = "date", format = "dd.MM.yyyy"),
@Mapping("items")})
public interface OrderJsonReader extends JsonReader<Order> {}
public static final OrderJsonReader ORDER = GWT.create(OrderJsonReader.class);
@Mappings({
@Mapping("product"),
@Mapping("amount")})
public interface OrderItemJsonReader extends JsonReader<OrderItem> {}
public static final OrderItemJsonReader ORDER_ITEM = GWT.create(OrderItemJsonReader.class);
@Mappings({
@Mapping("id"),
@Mapping("name"),
@Mapping("price")})
public interface ProductJsonReader extends JsonReader<Product> {}
public static final ProductJsonReader PRODUCT = GWT.create(ProductJsonReader.class);
}
When using external mappings there are a few things to notice:
- The @Mapping annotation must contain the properties name
- All mappings are collected in the @Mappings annotation
- The @Mappings annotation must be placed on the reader / writer interface
Sometimes you want to have both JSON and XML readers / writers. The mapping configuration is almost identical except for some path expressions of some fields. In this case you can use external mappings to overwrite the default path names:
{
"isbn": "978-0345417954",
"pages": 432,
"title": "The Hotel New Hampshire",
"author": {...},
"reviews": [...],
"related": [...]
}
978-0345417954
432
<title>The Hotel New Hampshire</title>
...
....
...
...
...
public class Book
{
@Mappings(@Mapping(value = "extraInfoOfLastRelatedBook", path = "@.related[2].extraInfo"))
public interface BookJsonReader extends JsonReader {}
public static final BookJsonReader JSON_READER = GWT.create(BookJsonReader.class);
@Mappings({@Mapping(value = "reviews", path = "reviews/review"),
@Mapping(value = "related", path = "related/book"),
@Mapping(value = "extraInfoOfLastRelatedBook", path = "//related/book[3]/extraInfo/text()")})
public interface BookXmlReader extends XmlReader<Book> {}
public static final BookXmlReader XML_READER = GWT.create(BookXmlReader.class);
String isbn;
int pages;
String title;
Author author;
List<String> reviews; // default path ok for JSON but not for XML
List<Book> related; // default path ok for JSON but not for XML
String extraInfoOfLastRelatedBook; // default path overwritten for JSON and XML
}