SerializerSets and ParserSets
On top of the serializers and parsers are the SerializerSet and ParserSet classes.
These classes allow serializers and parsers to be grouped and retrieved by W3C-compliant HTTP Accept and
Content-Type values.
When to use it
Use a set when you support several formats and choose one per request: you build the set once, then look up a serializer by the client's Accept header or a parser by its Content-Type.
For a single fixed format, use the serializer or parser directly.
The REST servlet API builds upon the SerializerSet and ParserSet classes to provide annotated REST servlets that
automatically negotiate the HTTP media types and allow the developer to work with requests and responses as POJOs.
Example
import org.apache.juneau.marshall.json.*;
import org.apache.juneau.marshall.parser.*;
import org.apache.juneau.marshall.serializer.*;
import org.apache.juneau.marshall.urlencoding.*;
public class SerializerSetExample {
public static class Person {
public String name;
public int age;
}
public static void main(String[] args) throws Exception {
// A serializer group with settings applied to every serializer.
SerializerSet serializers = SerializerSet.create()
.add(JsonSerializer.class, UrlEncodingSerializer.class)
.forEachWS(x -> x.ws())
.build();
// A parser group.
ParserSet parsers = ParserSet.create()
.add(JsonParser.class, UrlEncodingParser.class)
.build();
// Find the parser by Content-Type and read the body.
Person person = parsers
.getParser("text/json")
.orElseThrow()
.read("{\"name\":\"John Smith\",\"age\":45}", Person.class);
// Find the serializer by Accept value and write the result.
Object out = serializers
.getSerializer("text/invalid, text/json;q=0.8, text/*;q:0.6, */*;q=0.0")
.orElseThrow()
.write(person);
System.out.println(out);
}
}
A lookup returns an Optional.
An empty result means no serializer matched the Accept header (HTTP 406, Not Acceptable) or no parser matched the Content-Type (HTTP 415, Unsupported Media Type); the REST layer maps these to those status codes.
Options
| Builder method | Effect |
|---|---|
add(Class...) | Add serializers or parsers by class; the set builds each with its defaults. |
add(Serializer...) | Add already-built serializers (ParserSet takes parsers). |
forEach(Class, Consumer) | Apply a settings consumer to every member of the given type. |
forEachWS(Consumer) | Apply a settings consumer to every writer-based serializer. |
forEachOSS(Consumer) | Apply a settings consumer to every output-stream serializer. |
set(Class...) | Replace the current members with the given ones. |
copy() | Start a new builder from the contents of an existing set. |
clear() | Remove all members. |
build() | Create the immutable set. |
ParserSet.Builder has the same shape, with forEachRP (reader parsers) and forEachISP (input-stream parsers) in place of the serializer variants.