Java Reference
In-Depth Information
many embedded objects as needed. The following lines of code demonstrate the beginning and end of an embedded
object definition:
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("jsonJob", Json.createObjectBuilder()
.add("jobId", job.getJobId())
.add("division", job.getDivision())
.add("title", job.getTitle())
.add("salary", job.getSalary()));
It is also possible that a JsonObject may have an array of related sub-objects. Arrays can consist of objects, and
even hierarchies of objects, arrays, etc. In the example that follows, the “ jsonJob ” object consists of a single array.
Once a JsonObject has been created, it can be passed to a client. WebSockets work well for passing JsonObject s
back to a client, but there are a bevy of different technologies available for communicating with JSON. The following
example class utilizes an EJB call to obtain Jobs entities, which are then used to build a JSON object.
import java.io.StringWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import org.javaee7.entity.Jobs;
import org.javaee7.jpa.session.JobsSession;
@Named
public class JsonController {
@EJB
JobsSession jobsFacade;
public String buildJobs() {
List<Jobs> jobs = jobsFacade.findAll();
JsonObjectBuilder builder = Json.createObjectBuilder();
StringBuilder json = new StringBuilder();
for (Jobs job : jobs) {
builder.add("jsonJob", Json.createObjectBuilder()
.add("jobId", job.getJobId())
.add("division", job.getDivision())
.add("title", job.getTitle())
.add("salary", job.getSalary()));
JsonObject result = builder.build();
StringWriter sw = new StringWriter();
try (JsonWriter writer = Json.createWriter(sw)) {
writer.writeObject(result);
}
json.append(sw.toString());
}
return json.toString();
}
}
Search WWH ::




Custom Search