Skip to main content

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:

InstanceOutput
JsonSerializer.DEFAULTCompact JSON.
JsonSerializer.DEFAULT_READABLEJSON with whitespace and indentation.

For anything else, start from JsonSerializer.create(). The builder settings readers reach for first (all off by default):

Builder methodEffect
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:

Context.BuilderMarshallingContextable.BuilderMarshallingTraverseContext.BuilderSerializer.BuilderWriterSerializer.BuilderJsonSerializer.Builder

See also​