JsonWriter

Interface that can be used to write JSON output. Typically used to generate JSON when a dependency on a fully marshalling library (such as Jackson or Gson) cannot be assumed.

For standard Java types, the standard factory method may be used to obtain an instance of this interface. It supports String, Number and Boolean as well as Collection, Array, Map and WritableJson types. Typical usage would be:

JsonWriter<Map<String,Object>> writer = JsonWriter.standard();
writer.write(Map.of("Hello", "World!"), out);

More complex mappings can be created using the of method with a callback to configure the JSON members that should be written. Typical usage would be:

JsonWriter<Person> writer = JsonWriter.of((members) -> {
    members.add("first", Person::firstName);
    members.add("last", Person::lastName);
    members.add("dob", Person::dateOfBirth)
        .whenNotNull()
        .as(DateTimeFormatter.ISO_DATE::format);
});
writer.write(person, out);

The writeToString method can be used if you want to write the JSON directly to a String. To write to other types of output, the write method may be used to obtain a WritableJson instance.

Author

Phillip Webb

Moritz Halbritter

Since

3.4.0

Parameters

<T>

the type being written

Types

Link copied to clipboard
class Member<T>
A member that contributes JSON.
Link copied to clipboard
A path used to identify a specific JSON member.
Link copied to clipboard
class Members<T>
Callback used to configure JSON members.
Link copied to clipboard
Callback interface that can be applied to Members to change names or filter members.
Link copied to clipboard
interface PairExtractor<E>
Interface that can be used to extract name/value pairs from an element.
Link copied to clipboard
Callback interface that can be applied to Members to process values before they are written.

Functions

Link copied to clipboard
open fun <T> of(members: Consumer<JsonWriter.Members<T>>): JsonWriter<T>
Factory method to return a JsonWriter with specific member mapping.
Link copied to clipboard
open fun <T> standard(): JsonWriter<T>
Factory method to return a JsonWriter for standard Java types.
Link copied to clipboard
Return a new JsonWriter instance that appends a new line after the JSON has been written.
Link copied to clipboard
open fun withSuffix(suffix: String): JsonWriter<T>
Return a new JsonWriter instance that appends the given suffix after the JSON has been written.
Link copied to clipboard
open fun write(instance: T): WritableJson
Provide a WritableJson implementation that may be used to write the given instance to various outputs.
abstract fun write(instance: T, out: Appendable)
Write the given instance to the provided Appendable.
Link copied to clipboard
open fun writeToString(instance: T): String
Write the given instance to a JSON string.