Gson, Jackson, Primefaces and JSON-P

Posted by Tunde Michael | Sun Oct 9, 2016 06:25 PM | Viewed: 1132

JSON Processing

As exposing and consuming web services becomes our everyday life especially with JAX-RS 2.0 in Java EE 7 making exposing web services a piece of cake for Java developers, let’s talk about JSON (Javascript Object Notation) which has gradually become arguably the most used format of data exchange in web services.

It might sound unbelievable but the truth is many developers especially very young ones still generate JSON by concatenating strings if they even use JSON at all i.e 

String json = "{"
                + "\"firstname\":\"John\","
                + "\"lastname\":\"Doe\","
                + "\"phone\":\"2348xxxxx3477\","
                + "\"email\":\"john@johndoe.com\""
                + "}";

In this post I will examine 4 JSON processing libraries in Java that I’ve found myself using at one time or the other over the years. 

I created 2 simple single-file Netbeans project (An Ant and a Maven project) to demostrate how to configure these libraries in your project and demostrate their basic usage. I have provided links to some more useful resources if you wish to deepen your knowledge.

You can download the source codes for this tutorial from Github 

JsonLibAnt and JsonLibMaven

package com.tundemichael.blog.jsonlib;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

public class JsonLib {

    private static final Logger LOG = Logger.getLogger(JsonLib.class.getName());

    public static void main(String[] args) {
        try {
            System.out.println("================== Ant ====================");
            System.out.println("Concated String --> " + buildWithConcatedString());
            System.out.println("Built with Gson --> " + buildWithGson());
            System.out.println("Built with Jackson --> " + buildWithJackson());
            System.out.println("Built with Primefaces --> " + buildWithPrimefaces());
            System.out.println("Built with Java EE 7  --> " + buildWithJSONP());
            System.out.println("Built with Jenson --> " + buildWithGson());
        } catch (Exception e) {
            LOG.log(Level.SEVERE, null, e);
        }

    }

    public static String buildWithConcatedString() {
        String json = "{"
                + "\"firstname\":\"John\","
                + "\"lastname\":\"Doe\","
                + "\"phone\":\"2348xxxxx3477\","
                + "\"email\":\"john@johndoe.com\""
                + "}";
        return json;
    }

    public static String buildWithGson() {
        JsonObject json = new JsonObject();
        json.addProperty("firstname", "John");
        json.addProperty("lastname", "Doe");
        json.addProperty("phone", "2348xxxxx3477");
        json.addProperty("email", "john@johndoe.com");
        return json.toString();
    }

    public static String buildWithJackson() {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode json = mapper.createObjectNode();
        json.put("firstname", "John");
        json.put("lastname", "Doe");
        json.put("phone", "2348xxxxx3477");
        json.put("email", "john@johndoe.com");
        return json.toString();
    }

    public static String buildWithPrimefaces() throws JSONException {
        JSONObject json = new JSONObject();
        json.put("firstname", "John");
        json.put("lastname", "Doe");
        json.put("phone", "2348xxxxx3477");
        json.put("email", "john@johndoe.com");
        return json.toString();
    }

    public static String buildWithJSONP() {
        JsonObjectBuilder json = Json.createObjectBuilder();
        json.add("firstname", "John");
        json.add("lastname", "Doe");
        json.add("phone", "2348xxxxx3477");
        json.add("email", "john@johndoe.com");
        return json.build().toString();
    }

}

Each method in the above code represents one library (and string concatenation) i.e

buildWithConcatedString(); // String concatenation
buildWithGson(); // for Gson
buildWithJackson();  // for Jackson
buildWithPrimefaces(); // for primefaces
buildWithJSONP(); // for JSON Processing

All of them return a string. If you run the code, you will get the JSON string as below:

{"firstname":"John","lastname":"Doe","phone":"2348xxxxx3477","email":"john@johndoe.com"}

Now let's walk through the libraries and see how to configure each in our next project.

    1. GSON by Google

Gson by Google is one of the most popular libraries for JSON processing. Gson does conversion of java objects to json and vice-versa quite well. You can also use it to generate JSON from just about any arbitrary data.To use Gson in your next project, download the latest version from Maven Central Repository, extract the gson-2.7.jar to your classpath or if you’re a maven fan, setup Gson by adding the code below to your POM file:

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>

And we can simply create our method:

    public static String buildWithGson() {
        JsonObject json = new JsonObject();
        json.addProperty("firstname", "John");
        json.addProperty("lastname", "Doe");
        json.addProperty("phone", "2348xxxxx3477");
        json.addProperty("email", "john@johndoe.com");
        return json.toString();
    }

 

   2. Jackson 

To use all the rich features of Jackson, you need 3 jar files; Jackson core, Jackson Annotation and Jackson databind, although Jackson databind is the only one needed for this tutorial. The latest version as at the time of this writing is 2.8.3. 

If your project is Maven built, below is the dependency:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.3</version>
        </dependency>

And we can simply create our method:

    public static String buildWithJackson() {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode json = mapper.createObjectNode();
        json.put("firstname", "John");
        json.put("lastname", "Doe");
        json.put("phone", "2348xxxxx3477");
        json.put("email", "john@johndoe.com");
        return json.toString();
    }

 

    3. Primefaces Built-in JSON Library

If you're writing a JSF (Java Server Faces) application with Primefaces, there might not be need to use any external JSON library as Primeafces is bundled with a very handy JSON package:

org.primefaces.json

Also if you're using NetBeans IDE for non-JSF projects, Primefaces libraries are already bundled with NetBeans so you can just simply add it as a library to your project or download it at the official download page. For Maven projects, below is the dependency snippet:

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0</version>
        </dependency>

A caveat for Primeafces JSON library is the nasty exception it throws if you try to access a field that does not exist in the JSON data. So you must either be sure of the fields or handle JSONException properly.

    public static String buildWithPrimefaces() throws JSONException {
        JSONObject json = new JSONObject();
        json.put("firstname", "John");
        json.put("lastname", "Doe");
        json.put("phone", "2348xxxxx3477");
        json.put("email", "john@johndoe.com");
        return json.toString();
    }

 

  4. Java API for JSON Processing (JSR 353)

Just as you dont need to add external JSON library to your JSF/Primeafces project, you dont need to add any external library for JSON processing for your next Java EE 7 projects. If you're not writing a Java EE 7, then download the jar file at https://repo1.maven.org/maven2/org/glassfish/javax.json/ or setup your maven project with the dependency below:

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.0.4</version>
        </dependency>

 and we can simply use the library as below:

    public static String buildWithJSONP() {
        JsonObjectBuilder json = Json.createObjectBuilder();
        json.add("firstname", "John");
        json.add("lastname", "Doe");
        json.add("phone", "2348xxxxx3477");
        json.add("email", "john@johndoe.com");
        return json.build().toString();
    }

 

This post is what it is, a bare-bone introduction to these libraries. For further reading on the other one thousand and one things you can do with each of them, please check the following links:

 

 

 

 


Share this post
facebook twitter googleplus linkedin





Comments (0)


Newsletter: Never miss a thing