Java Reference
In-Depth Information
This example part of a JSF application, specifically a CDI named bean.
We are only showing code that is relevant to the discussion.
In this example, we are generating a JSON representation of a simple Person Java
class containing a few simple properties such as firstName , middleName , lastName ,
and so on, along with the corresponding getter and setter methods.
The first thing we do in our example is obtain an instance of a class implementing
the JsonObjectBuilder interface by invoking the static createObjectBuilder()
method on the Json class. This method returns an instance of a class implementing
the JsonObjectBuilder interface, which we can use as a starting point to generate
a JSON representation of a Java object.
Once we obtain an instance of JsonObjectBuilder , we need to invoke one of its
overloaded add() methods, all of which accept a string as their first parameter
and a value as its second parameter. This method returns another instance of
JsonObjectBuilder , as seen in our example. We can chain invocations of the add()
method to quickly and easily generate the final JSON representation we need. What
we are seeing here is the builder pattern in action.
In our example, we used two versions of the JsonObjectBuilder.add() method,
one accepting a string as its second parameter and another one accepting an integer
as its second parameter. (In our example, we passed an Integer object to this
method. Java unboxing takes care of converting our parameter to an int primitive)
There are several other overloaded versions of JsonObjectBuilder.add() . This
allows great flexibility when building JSON representations of Java objects via the
JSON-P object model API. The following table describes all overloaded versions of
JsonObjectBuilder.add() ; in all cases, the first parameter corresponds to the name
of the JSON property on the generated JSON object, and the second parameter is the
corresponding value in the generated JSON.
add method
Description
add(String name, BigDecimal
value)
This adds a JsonNumber representation of
a BigDecimal value to the generated JSON
object
add(String name, BigInteger
value)
This adds a JsonNumber representation of
a BigInteger value to the generated JSON
object
add(String name, boolean
value)
This adds either a JsonValue.TRUE or
JsonValue.FALSE value to the generated
JSON object, depending on the Boolean value
passed as a parameter
Search WWH ::




Custom Search