Marshalling
Juneau uses Parsers and Serializers for marshalling HTTP request and response bodies to POJOs using the Content-Type
header to match the best parser and the Accept
header to match the best serializer.
Serializers and parsers can be associated with REST servlets using the following annotations:
Request bodies are parsed and passed in via @Content-annotated parameters, and response bodies are returned or thrown by @RestOp-annotated methods and serialized.
@Rest(
serializers={JsonParser.class, HtmlSerializer.class},
parsers={JsonParser.class, HtmlParser.class}
)
public class MyResource {
// Override at the method level.
@RestPost(parsers={XmlParser.class})
public MyPojo myMethod(@Content MyPojo myPojo) {
// Do something with your parsed POJO.
// Then return it and serialize the POJO.
}
}
The following classes provide common default serializers and parsers that can be used as-is or augmented by child classes:
Serializers and parsers can also be defined programmatically using an INIT hook method like shown below:
@Rest
public class MyResource {
@RestInit
public void init(RestContext.Builder builder) {
builder.serializers().add(JsonSerializer.class, HtmlSerializer.class);
builder.parsers().add(JsonParser.class, HtmlParser.class);
}
}
They can also be defined through custom REST contexts and builders.
Config annotations allow you to define serializer and parser properties using specialized annotations at either the class or operation levels:
@Rest(
...
)
@BeanConfig(sortProperties="true")
@SerializerConfig(trimNulls="true")
@JsonConfig(escapeSolidus="true")
public class MyResource extends BasicRestServlet {
@RestPost
@BeanConfig(sortProperties="false")
@SerializerConfig(trimNulls="false")
public MyPojo myMethod(@Content MyPojo myPojo) {
...
}
}
Swaps are associated serializers and parsers registered on a REST resource via the BeanConfig annotation on either the class or method level:
// Servlet with transforms applied
@Rest(
...
)
@BeanConfig(
swaps={
// Calendars should be serialized/parsed as ISO8601 date-time strings
TemporalCalendarSwap.IsoInstant.class,
// Byte arrays should be serialized/parsed as BASE64-encoded strings
ByteArraySwap.Base64.class
},
beanFilters={
// Subclasses of MyInterface will be treated as MyInterface objects.
// Bean properties not defined on that interface will be ignored.
MyInterface.class
}
)
public MyResource extends BasicRestServlet {...}
Config annotations are defined for all serializers and parsers: