Parsers
REST resources use the {@link oaj.parser.Parser} API for defining parsers for parsing request
body content and converting them into POJOs.
The servlet will pick which parser to use by matching the request Content-Type header with the
media types defined through the {@link oaj.parser.Parser#getMediaTypes()} method.
Parsers can be associated with REST servlets in the following ways:
-
{@link oajr.annotation.Rest#parsers() Rest(parsers)}
- Annotation on resource Java class.
-
{@link oajr.annotation.RestMethod#parsers() RestMethod(parsers)}
- Annotation on resource Java method.
-
{@link oajr.RestContextBuilder#parsers(Class[])}
- Programmatic.
The following are all equivalent ways of defining parsers used by a resource:
// Option #1 - Defined via annotation.
@Rest(parsers={JsonParser.class, XmlParser.class})
public class MyResource {
// Option #2 - Defined via builder passed in through resource constructor.
public MyResource(RestContextBuilder builder) throws Exception {
// Using method on builder.
builder.parsers(JsonParser.class, XmlParser.class);
// Same, but use pre-instantiated parsers.
builder.parsers(JsonParser.DEFAULT, XmlParser.DEFAULT);
// Same, but using property.
builder.set(REST_parsers, JsonParser.class, XmlParser.class);
}
// Option #3 - Defined via builder passed in through init method.
@RestHook(INIT)
public void init(RestContextBuilder builder) throws Exception {
builder.parsers(JsonParser.class, XmlParser.class);
}
// Override at the method level.
@RestMethod(parsers={HtmlParser.class})
public Object myMethod(@Body MyPojo myPojo) {
// Do something with your parsed POJO.
}
}
- {@link oajr.RestContext#REST_parsers}