Over a million developers have joined DZone.

Test driving Java API for Processing JSON with GlassFish 4.0

DZone's Guide to

Test driving Java API for Processing JSON with GlassFish 4.0

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Writing and contributing to a specification is one thing. Working with it and looking into real examples is a pre-condition if you want to give valuable feedback. The latest promoted GlassFish builds contain the renaming to 4.0 and I thought it might be a good time to give the Java API for Processing JSON (JSON-P) a test drive.

Get Java EE 7 enabled GlassFish 4.0 
First thing to do is to grab a copy of latest Java EE 7 enabled GlassFish 4.0 from the promoted builds. I am using the GlassFish Server Open Source Edition 4.0 (build 77) which seems to be quite stable. But in general, if you are trying this please keep in mind, that the promoted builds are basically development and unstable versions of ongoing work for GlassFish 4.0. It wouldn't make much sense to complain about them.  Unzip the download into a suitable location.

For a later step you need to update the JSON-P RI within the modules directory. Follow Arun's Blog about getting and building the JSON-P RI and copy the jsonp~git\impl\target\javax.json-1.0-SNAPSHOT.jar to the glassfish4\glassfish\modules\javax.json.jar. Make sure to make a copy of the original in case you do something wrong in that step. If you are feeling uncomfortable with that you can also skip it and select a different dependency later on ... The fact is, that the JSON-P API changed that much over the past few months, that the GlassFish included b02 isn't appropriate anymore to show you anything. So, for now, we have to tweak it a bit.
Afterwards you are all set to integrate your fresh GlassFish install into your favorite IDE which could be NetBeans.

Create a new Java EE 7 Project
The Java EE 7 archetype is located in the codehaus.org snapshot repository. In order to use it via NetBeans effectively you have to configure the repository on the "Services" tab under "Maven Repositories". The repository URL is https://nexus.codehaus.org/content/repositories/snapshots/. It might take a while to process the index. After that, proceed with the "New Project > Maven > Project from Archetype" wizard and enter "webapp-javaee7" into the search box. Select the 0.1-SNAPSHOT and click "Finish". Alternatively you can always go with the following command line:

mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeVersion=0.1-SNAPSHOT -DarchetypeRepository=https://nexus.codehaus.org/content/repositories/snapshots/ -DgroupId=net.eisele.sample -DartifactId=javaee7-jsonp -Dversion=1.0-SNAPSHOT -Dpackage=net.eisele.javaee7jsonp -Darchetype.interactive=false --batch-mode --update-snapshots archetype:generate

Now open the project and edit the pom.xml. Change the scope of the javaee-web-api to provided and add the json-api dependency as shown below:
Please make sure to use the version 1.0-SNAPSHOT and _not_ the officially documented 1.0-b02. We want to use the latest snapshot we build in the first paragraph with all the new APIs :) If you decided not to go the "build it your own way" you can simply use the 1.0-b04 from maven central. This also works. Please make sure to have exactly this order of dependencies. If not, you will use the old b02 which is included with the javaee-web-api dependency :( Did someone say, Maven is easy? :)
That's it for now. Let's create a simple JAX-RS endpoint.

Adding a JAX-RS Person Resource
First thing to do is to write the basic JAX-RS resource. You can do this via the NetBeans' "RESTful Web Services from Pattern" wizard or yourself by simply outlining a brief class like the following:
public class PersonResource {
    public PersonResource() {
    public String getJson() {
        return "[]";
This class needs to be registered. You can either use Jerseys servlet mechanism to do this or register it yourself with the application specific ApplicationConfig:
public class ApplicationConfig extends Application {
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        return resources;
Wow .. that should be all for now. You should give it a test drive. Deploy it to your domain and try http://localhost:8080/javaee7-jsonp/webresources/person. It should simply print the empty brackets []. Now it is time to get some JSON-P into the mix.

Building JSON Objects with JSON-P
We are going to build a JSON representation of a person with the DOM-based API. Replace the return statement in the PersonResource with the following code:
JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add("person", Json.createObjectBuilder()
                .add("firstName", "Markus")
                .add("lastName", "Eisele"));
        JsonObject result = builder.build();
        StringWriter sw = new StringWriter();
        try (JsonWriter writer = Json.createWriter(sw)) {
        return sw.toString()
And now lets use my most favorite Chrome extension to look at what we've got:
It obviously works. Turning this the other way round would mean to read incoming JSON. This could look like the following:
        String json = "{\n"
                + "    \"person\": {\n"
                + "        \"firstName\": \"Markus\",\n"
                + "        \"lastName\": \"Eisele\"\n"
                + "    }\n"
                + "}";
        JsonReader jr = Json.createReader(new StringReader(json));
        JsonValue value = jr.readObject();
Beside the DOM-API you also have a Streaming-API which uses a
JsonGenerator generator = Json.createGenerator(new FileWriter(..))
JsonParser parser = Json.createParser(new StringReader(...));
to generate and parse JSON. Have a look at the latest JavaDoc for a complete reference. Go ahead and test drive yourself. The EG is still looking for feedback, so it might be a good idea to jump on the users list and send along your thoughts. I am also happy to read your ideas here!

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.


Published at DZone with permission of Markus Eisele, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}