Jackson JsonGenerator
Jakob Jenkov |
The Jackson JsonGenerator
is used to generate JSON from Java objects (or whatever data structure your
code generates JSON from).
Creating a JsonGenerator
In order to create a Jackson JsonGenerator
you must first create a JsonFactory
instance.
Here is how you create a JsonFactory
:
JsonFactory factory = new JsonFactory();
Once you have created the JsonFactory
you can create the JsonGenerator
using the
createGenerator()
method of the JsonFactory
. Here is an example of creating a
JsonGenerator
:
JsonFactory factory = new JsonFactory(); JsonGenerator generator = factory.createGenerator( new File("data/output.json"), JsonEncoding.UTF8);
The first parameter of the createGenerator()
method is the destination of the generated JSON.
In the example above the parameter is a File
object. This means that the generated JSON will be
written to the given file. The createGenerator()
method is overloaded, so there are other versions
of the createGenerator()
method which takes e.g an OutputStream
etc., giving you
different options about where to write the generated JSON to.
The second parameter of the createGenerator()
method is the character encoding to use when generating
the JSON. The example above uses UTF-8 .
Generating JSON With The JsonGenerator
Once you have created a JsonGenerator
you can start generating JSON. The JsonGenerator
contains a set of write...()
methods which you can use to write the various parts of a JSON object.
Here is a simple example of generating JSON with the Jackson JsonGenerator
:
JsonFactory factory = new JsonFactory(); JsonGenerator generator = factory.createGenerator( new File("data/output.json"), JsonEncoding.UTF8); generator.writeStartObject(); generator.writeStringField("brand", "Mercedes"); generator.writeNumberField("doors", 5); generator.writeEndObject(); generator.close();
This example first calls writeStartObject()
which writes a {
to the output. Then
the example calls writeStringField()
which writes the brand
field name + value to the
output. After that the writeNumberField()
method is called which writes the doors
field name + value to the output. Finally, the writeEndObject()
is called which writes a }
to the output.
The JsonGenerator
has many other write methods you can use. This example only showed a few of them.
Closing the JsonGenerator
Once you have finished generating the JSON you should close the JsonGenerator
. You do so by calling
its close()
method. Here is how closing the JsonGenerator
looks like:
generator.close();
Closing the JsonGenerator
will also close the file or OutputStream
etc. whereto the
JsonGenerator
writes the generated JSON.
Tweet | |
Jakob Jenkov |