Class JsonSerializer

All Implemented Interfaces:
Function<Object,String>, ThrowingFunction<Object,String>, JsonMetaProvider, ArrayRecordWritable, RecordWritable, TokenWritable
Direct Known Subclasses:
JcsSerializer, Json5Serializer, JsonlSerializer, JsonSchemaSerializer, JsonSerializer.Readable

Serializes POJO models to RFC 8259 JSON.

Produces strict JSON with double-quoted strings by default. For JSON5-style output (single quotes, etc.), use Json5Serializer.

Media types

Handles Accept types: application/json, text/json

Produces Content-Type types: application/json

Description

The conversion is as follows...

  • Maps (e.g. HashMaps, TreeMaps) are converted to JSON objects.
  • Collections (e.g. HashSets, LinkedLists) and Java arrays are converted to JSON arrays.
  • Strings are converted to JSON strings.
  • Numbers (e.g. Integer, Long, Double) are converted to JSON numbers.
  • Booleans are converted to JSON booleans.
  • nulls are converted to JSON nulls.
  • arrays are converted to JSON arrays.
  • beans are converted to JSON objects.

The types above are considered "JSON-primitive" object types. Any non-JSON-primitive object types are transformed into JSON-primitive object types through ObjectSwaps associated through the MarshallingContext.Builder#swaps(Class...) method. Several default transforms are provided for transforming Dates, Enums, Iterators, etc...

This serializer provides several serialization options. Typically, one of the predefined DEFAULT serializers will be sufficient. However, custom serializers can be constructed to fine-tune behavior.

Behavior-specific subclasses

The following direct subclasses are provided for convenience:

Example:

// Use one of the default serializers to serialize a POJO String json = JsonSerializer.DEFAULT.write(someObject); // Create a custom serializer for lax syntax using single quote characters JsonSerializer serializer = Json5Serializer.create().build(); // Clone an existing serializer and modify it to use single-quotes serializer = JsonSerializer.DEFAULT.copy().sq().build(); // Serialize a POJO to JSON String json = serializer.write(someObject);

Example output (Map of name/age):

{"name":"Alice","age":30}

Complex (nested object + array):

{"name":"Alice","age":30,"address":{"street":"123 Main St","city":"Boston","state":"MA"},"tags":["a","b","c"]}

Notes:
  • This class is thread safe and reusable.
See Also: