JSON Serializers
The JsonSerializer class serializes POJOs (beans, collections, maps and simple values) into JSON text.
When to use it
Use JsonSerializer when you need strict JSON output, for example a REST response or a file another tool reads.
For a one-line conversion with the default settings, the Json marshaller (Json.of(pojo)) is shorter; see Marshallers.
For JSON5 output (unquoted keys, single quotes), use Json5Serializer instead; see JSON 5.
Example
import org.apache.juneau.marshall.json.*;
public class JsonSerializerExample {
public static class Person {
public String name = "John Smith";
public int age = 45;
public String nickname;
}
public static void main(String[] args) throws Exception {
// Compact output with the default serializer: {"age":45,"name":"John Smith"}
String compact = JsonSerializer.DEFAULT.write(new Person());
// A serializer with whitespace that also writes null properties.
JsonSerializer serializer = JsonSerializer.create().ws().keepNullProperties().build();
String readable = serializer.write(new Person());
System.out.println(readable);
}
}
The second serializer prints:
{
"age": 45,
"name": "John Smith",
"nickname": null
}
Serializers are immutable and thread-safe, so build one once and reuse it.
Options
The pre-configured instances cover the common cases:
| Instance | Output |
|---|---|
JsonSerializer.DEFAULT | Compact JSON. |
JsonSerializer.DEFAULT_READABLE | JSON with whitespace and indentation. |
For anything else, start from JsonSerializer.create(). The builder settings readers reach for first (all off by default):
| Builder method | Effect |
|---|---|
ws() | Add whitespace and indentation (same as useWhitespace()). |
sq() | Use single quotes instead of double quotes. |
keepNullProperties() | Write bean properties whose value is null. |
trimEmptyCollections() / trimEmptyMaps() | Omit empty collections and maps. |
sortCollections() / sortMaps() | Sort collection entries and map keys. |
addBeanTypes() | Add _type properties so a parser can rebuild the original classes. |
The builder inherits from this hierarchy, and each level's Javadoc lists the full set of settings:
See also
- JSON Parsers: the reverse direction.
- JSON Methodology: how POJOs map to JSON types.
- @Json Annotation: per-class and per-property JSON settings.
- JSON 5
- Serializers and Parsers