Generating the JSON representation from the object model
Generating the JSON representation from the object model
In the previous section, we discussed the APIs provided by JSR 353 to convert the JSON data into the Java object model. In this section, you will learn how to convert a Java object model into the JSON format, which is the opposite of the operation discussed in the previous section.
The very first step is to build an object model. You can use either of the following classes to generate the object model. The choice of the builder class depends on whether you want to generate a JSON object or a JSON array:
- javax.json.JsonObjectBuilder: This builder class is used for generating the JSON object model from scratch. This class provides methods to add the name-value pairs to the object model and to return the final object.
- javax.json.JsonArrayBuilder: This builder class is used for generating an array of JSON objects from scratch. This class provides methods to add objects or values to the array model and to return the final array.
The builder classes can be created either from the javax.json.Json factory class or from the javax.json.JsonBuilderFactory class. You may go for JsonBuilderFactory if you want to override the default configurations for the generated objects (configurations are specific to vendors) or if you need to create multiple instances of the builder classes.
The following code snippet illustrates the use of the JsonArrayBuilder APIs for converting an array of the employee objects into the JSON array. The client builds the JSON objects by using JsonObjectBuilder and adds them to JsonArrayBuilder. Finally, when the client calls the build() method, JsonArrayBuilder returns the associated JSON array:
The resulting file output content may look like the following:
Comments
Post a Comment