Java Reference
In-Depth Information
Generating JSON data with the JSON-P object
model API
When using the JSON-P object model API, we typically start by invoking the
add()
method of an implementation of the
JsonObjectBuilder
interface. This method
returns an instance of another
JsonObjectBuilder
interface implementation. We can
chain invocations of
JsonObject.add()
together, allowing us to easily create a JSON
representation from a Java object. The following example illustrates this process:
package com.ensode.jsonpmodelapi;
//imports omitted
@Named
@RequestScoped
public class JsonPModelApiBean {
@Inject
private Person person;
private String jsonStr;
public String generateJson() {
JsonObjectBuilder jsonObjectBuilder =
Json.createObjectBuilder();
JsonObject jsonObject = jsonObjectBuilder.
add("firstName", person.getFirstName()).
add("middleName", person.getMiddleName()).
add("lastName", person.getLastName()).
add("gender", person.getGender()).
add("age", person.getAge()).
build();
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter))
{
jsonWriter.writeObject(jsonObject);
}
setJsonStr(stringWriter.toString());
//JSF Dynamic navigation
return "generated_json";
}
//other methods omitted
}