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
the type being written