Java Reference
In-Depth Information
Once created, the
JsonObject
can be passed to a client for processing. In this example, the object sections are
printed to the server log, and the output looks similar to the following:
{"jsonJob":{"jobId":1,"division":"IT","title":"IT TITLE A","salary":60000}}
Persisting JSON
The
JsonWriter
class can be utilized to write a
JsonObject
to a Java writer object. A
JsonWriter
is instantiated by
passing a
Writer
object as an argument. Instantiating a
JsonWriter
will prepare the Writer object that had been
passed as an argument to write JSON format. After that
Writer
has been created, the
JsonWriter writeObject()
method can be invoked, passing the
JsonObject
that is to be written. Once the
JsonObject
has been written, the
JsonWriter
can be closed by calling its
close()
method. These are the only steps that are necessary for writing a
JSON object to a Java
Writer
class type.
The example below goes one step further and writes the JSON object to disk. In this case, a
StringWriter
encapsulates the
JsonWriter
. To do so, a new
FileWriter
is instantiated, passing the name of the file that we wish
to create. Next, a
BufferedWriter
is created, passing the
FileWriter
that was previously instantiated. Lastly, the
contents of the
StringWriter
that contains the JSON object is written to the
BufferedWriter
by calling
out.write()
.
Doing so writes the content to the File that was created. When this process is complete, a new JSON object will have
been written to disk.
The following example utilizes the JSON-P API to build a JSON object, and then store it to the file system. The
JsonWriter
class makes it possible to create a file on disk and then write the JSON to that file.
public void writeJson() {
try {
JsonObject jsonObject = jsonController.buildJobsJson();
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(writer);
jsonWriter.writeObject(jsonObject);
jsonWriter.close();
writer.close();
// Write file
FileWriter fstream = new FileWriter("Jobs.json");
BufferedWriter out = new BufferedWriter(fstream);
out.write(writer.toString());
out.close();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "JSON Built",
"JSON Built"));
} catch (IOException ex) {
System.out.println(ex);
}
}
Parsing JSON
In order to perform some tasks, a JSON object must be searched to find only the content that is desired and useful
for the current task. Utilizing a JSON parser can make jobs such as these easier, as a parser is able to break the
object down into pieces so that each different name/value pair or attribute can be examined as needed to locate the
desired result.