Java Reference
In-Depth Information
add method
Description
add(String name, double value)
This adds a JsonNumber representation of a
double value to the generated JSON object
add(String name, int value)
This adds a JsonNumber representation of
an int value to the generated JSON object
add(String name,
JsonArrayBuilder builder)
This adds an array of JSON objects to the
generated JSON object
add(String name,
JsonObjectBuilder builder)
This adds another JSON object to the
generated JSON object
add(String name, JsonValue
value)
This adds an implementation of the
JsonValue interface to the generated JSON
object
add(String name, long value)
This adds a JsonNumber representation of a
long value to the generated JSON object
add(String name, String value)
This adds a string value to the generated
JSON object
Lets go back to our example. After invoking the chain of add() methods, we invoke
the build() method on the resulting JsonObjectBuilder implementation. This
method invocation returns an instance of a class implementing JsonObject .
Once we have a JsonObject implementation, typically we would want to convert
it to its string representation. To convert a JsonObject implementation to a JSON
string, we need to invoke the static createWriter() method on the Json class,
passing a new instance of StringWriter as a parameter. This method returns an
instance of a class implementing the JsonWriter interface. Now, we need to invoke
the writeObject() method of JsonWriter , passing the JsonObject instance
we previously created as a parameter. This method invocation populates the
StringWriter object we used to create our JsonWriter interface. We can obtain
the JSON string representation of our object by simply invoking the toString()
method of our StringWriter object.
Our example in action
Our example consists of a simple web application that uses JSF to populate a CDI
named bean and generates a JSON string from this bean. The markup for our simple
JSF page populating the CDI named bean is as follows:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
Search WWH ::




Custom Search