Comparing Jackson vs JSONB

JSON-B and Jackson are both libraries that can be used for parsing and generating JSON data in Java. However, they have some differences in their functionality and usage. This tutorial will discuss them in detail.

Jackson and JSON-B in a nutshell

Firstly, if you are new to JSON parsing, let’s give an overview to these two libraries:

  • Jackson is a widely used and well-established library for working with JSON in Java. It provides a full suite of JSON processing capabilities, including parsing, generating, and manipulating JSON data. It is highly customizable and can be used to handle a wide variety of JSON formats and use cases.
  • JSON-B is the reference implementation of JSR-367, which is an official standard for JSON binding in Java. It provides a simple and easy-to-use API for converting between Java objects and JSON, and supports many of the features of JSON-P (Java API for JSON Processing) and JSON-P-1.1. JSON-B is designed to be easy to use and requires minimal configuration and setup.

In summary, both libraries can be used for parsing and generating JSON data in Java. However, Jackson is a more mature library with more features and customizations, while JSON-B is a more recent library and is designed to be more simple to use, it is an official standard for JSON binding in Java.

To summarize check the following table:

FeatureJacksonJSON-B
Support for JSON processingYesYes
Support for JSON serialization and deserializationYesYes
Support for handling JSON data in a reactive wayNo No
Standard implementationNoYes (JSR-367)
Customization and fine-grained controlHighLow
Ease of useModerateVery simple
Community and ecosystemLarge and establishedSmaller

Next, let’s see some concrete examples for both libraries.

Jackson Example

In our first example, we will show how to parse a JSON String using the Jackson library:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) throws IOException {
        String jsonData = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"Street 1\",\"city\":\"City 1\"}}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(jsonData);

        String name = jsonNode.get("name").asText();
        int age = jsonNode.get("age").asInt();
        String street = jsonNode.get("address").get("street").asText();
        String city = jsonNode.get("address").get("city").asText();

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Street: " + street);
        System.out.println("City: " + city);
    }
}

Once the JsonNode is created, it can navigate through the json tree using the get method, which returns a JsonNode object. The asText() method is used to get the value of the node as a String and asInt() method is used to get the value of the node as an Integer. Finally, the values are printed to the console.

Then, here’s an example of converting a Java object to JSON using the Jackson library:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) throws JsonProcessingException {
        Address address = new Address("Street 1", "City 1");
        Person person = new Person("John", 30, address);

        ObjectMapper mapper = new ObjectMapper();
        String jsonData = mapper.writeValueAsString(person);
        System.out.println(jsonData);
    }
}

When a Java object is serialized into JSON, Jackson includes all of its properties by default. However, in some cases, you may want to exclude certain properties from being serialized, either because they are irrelevant, or because they contain sensitive information that should not be exposed.

To achieve this, you can add the @JsonIgnoreProperties annotation to the class and specify the names of the properties that you want to ignore. For example, consider the following class:

@JsonIgnoreProperties({ "secretKey", "password" })
public class User {
    private String username;
    private String password;
    private String email;
    private String secretKey;
    // constructors, getters, setters, etc.
}

In this above example, the @JsonIgnoreProperties annotation allows to ignore the secretKey and password properties during serialization and deserialization of the User class.

Besides, the @JsonIgnoreProperties(ignoreUnknown = false) annotation has the effect of instructing the Jackson library to throw an exception if the JSON file contains an unknown property during the serialization.

Finally, in order to use Jackson in your Maven project, add the following library:

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

JSON-B Example

Firstly, let’s check an example which shows how to parse JSON data using the JSON-B library:

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;

public class JSONBExample {
    public static void main(String[] args) {
        String jsonData = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"Street 1\",\"city\":\"City 1\"}}";
        Jsonb jsonb = JsonbBuilder.create();
        Person person = jsonb.fromJson(jsonData, Person.class);
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
        System.out.println("Street: " + person.getAddress().getStreet());
        System.out.println("City: " + person.getAddress().getCity());
    }
}

Jsonb is the main entry point for the JSON-B API, and it provides methods for serializing Java objects to JSON and deserializing JSON to Java objects. The Jsonb class is an interface, and it can be created using the JsonbBuilder class.s.

In order to create a Java Object from a JSON String, you can use the method fromJson of the Jsonb interface.

On the other hand, in order to convert a Java object to JSON, you will use the equivalent toJson method of the Class Jsonb:

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;

public class JSONBExample {
    public static void main(String[] args) {
        Address address = new Address("Street 1", "City 1");
        Person person = new Person("John", 30, address);
        Jsonb jsonb = JsonbBuilder.create();
        String jsonData = jsonb.toJson(person);
        System.out.println(jsonData);
    }
}

In JSON-B, you can use the @JsonbTransient annotation to ignore properties during serialization and deserialization. For example:

public class User {
    private String username;
    private String password;
    @JsonbTransient
    private String email;
    // constructors, getters, setters, etc.
}

In this example, the email property contains the @JsonbTransient annotation, which means to ignore it during JSON serialization and deserialization.

Then, to throw an Exception if the JSON file contains an unknown property, you can set in your JsonbConfig the following property:

JsonbConfig config = new JsonbConfig().setProperty(JsonbConfig.PROPERTY_IGNORE_UNKNOWN_PROPERTIES, false);

Finally, to build your JSONB project, you will need to add the following dependency in your project:

<dependency>
    <groupId>jakarta.json.bind</groupId>
    <artifactId>jakarta.json.bind-api</artifactId>
    <scope>provided</scope>
</dependency>

Conclusion

Both Jackson and JSONB are capable of parsing JSON data, but the way of doing it is quite different. Jackson uses a tree-based model to represent JSON data, which allows for more fine-grained control and manipulation of the data. JSON-B, on the other hand, uses a more object-oriented approach, where JSON data is mapped directly to Java objects. Each library has its own strengths and weaknesses, and the choice of which to use will depend on the specific requirements of your project and your personal preferences.

Found the article helpful? if so please follow us on Socials