Jsonb provides an abstraction over the JSON Binding framework operations:
-
fromJson: read JSON input, deserialize to Java objects content tree
-
toJson: serialize Java objects content tree to JSON input
Instance of this class is created using
javax.json.bind.JsonbBuilderbuilder methods:
// Example 1 - Creating Jsonb using default JsonbBuilder instance provided by default JsonbProvider
Deserializing (reading) JSON
Can de-serialize JSON data that represents either an entire JSON
document or a subtree of a JSON document.
Reading (deserializing) object content tree from a File:
Jsonb jsonb = JsonbBuilder.create();
Book book = jsonb.fromJson(new FileReader("jsonfile.json"), Book.class);
If the deserialization process is unable to deserialize the JSON content to an object
content tree, fatal error is reported that terminates processing by
throwing JsonbException.
Serializing (writing) to JSON
Serialization writes the representation of a Java object content tree into
JSON data.
Writing (serializing) object content tree to a File:
jsonb.toJson(object, new FileWriter("foo.json"));
Writing (serializing) to a Writer:
jsonb.toJson(object, new PrintWriter(System.out));
Encoding
In deserialization operations (
fromJson), encoding of JSON data is detected automatically.
Use the
javax.json.bind.JsonbConfig API to configure expected
input encoding used within deserialization operations. Client applications are
expected to supply a valid character encoding as defined in the
RFC 7159 and supported by Java Platform.
In serialization operations (
toJson), UTF-8 encoding is used by default
for writing JSON data.
Use the
javax.json.bind.JsonbConfig API to configure the
output encoding used within serialization operations. Client applications are
expected to supply a valid character encoding as defined in the
RFC 7159 and supported by Java Platform.
For optimal use,
JsonbBuilder and
Jsonb instances should be
reused - for a typical use-case, only one
Jsonb instance is
required by an application.
All the methods in this class are safe for use by multiple concurrent threads.
Calling
Closable.close() method will cleanup all CDI managed components
(such as adapters with CDI dependencies) created during interaction with Jsonb.
Calling
close() must be done after all threads has finished interaction with Jsonb.
If there are remaining threads working with Jsonb and
close() is called, behaviour is undefined.