Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Jackson's ObjectMapper With Optionals

DZone's Guide to

Using Jackson's ObjectMapper With Optionals

While you shouldn't use Optional more than you need to, there's no doubt that they offer benefits. Here, we examine bringing Jackson in to augment Optional's use.

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Today, to warm up (it’s actually my first essential post), I want to share with you simple trick that might be useful when mapping Java objects to JSON.

Ok, so let’s start with some code. Consider, you’re writing some e-commerce application in which there are entities like Offer and Category. Let’s say an offer has some category, and categories can have subcategories.

package com.krzysztofgadomski.jacksonobjectmapperwithoptionals;

import java.util.Optional;

class Category {
    private final int id;
    private final String name;
    private final Optional<Category> parentCategory;

    Category(int id, String name, Optional<Category> parentCategory) {
        this.id = id;
        this.name = name;
        this.parentCategory = parentCategory;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Optional<Category> getParentCategory() {
        return parentCategory;
    }
}


First, I must mention that I DO NOT encourage you to apply this kind of model presented above. However, I also do not want to say it is bad.

You probably already have noticed what I am talking about — java.util.Optional was not meant to be used this way.

This is the quote from the OpenJDK mailing list:

The JSR-335 EG felt fairly strongly that Optional should not be on any more than needed to support the optional-return idiom only.

Someone suggested maybe even renaming it to OptionalReturn

As you can see, we are breaking at least two rules:

  • We have Optional as a field of a POJO class.
  • We pass Optional in a constructor.

The second can easily be fixed  by modifying a constructor a little:

...
    private final Optional<Category> parentCategory;

    Category(int id, String name, Category parentCategory) {
        this.id = id;
        this.name = name;
        this.parentCategory = Optional.ofNullable(parentCategory);
    }
...


But still, Optional as a class field remains.

There are many great articles on the Internet and discussions on StackOverflow about how Optionals should be used. These are the two I like the most, and they present opposing positions.

In the case of the first one, read the comments, too – you will see how the community is divided.

So, because there are a lot of enthusiasts on both ways of using Optionals, I will not judge here, and the decision of whether the above POJO is good or bad is up to you. (A few months ago, I had to code similar stuff. Personally, I am closer to the original intention for Optional usage — at the end of the post, I will describe solution I’ve chosen.)

No matter which solution you choose, you can’t deny that having Optional parentCategory as a field in Category class makes a real model. They can be root categories that have no parent, and child categories also.

Let’s say we want to stay with this model, and then we want to represent category objects in JSON format (afer this too-long introduction, we are slowly approaching the merits! :D)

The most common way is to use the Jackson library.

package com.krzysztofgadomski.jacksonobjectmapperwithoptionals;

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

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        Category motorization = new Category(1, "Motorization", null);
        Category cars = new Category(2, "Cars", motorization);
        Category motorcycles = new Category(3, "Motorcycles", motorization);

        ObjectMapper objectMapper = new ObjectMapper();

        System.out.println(objectMapper.writeValueAsString(motorization));
        System.out.println(objectMapper.writeValueAsString(cars));
        System.out.println(objectMapper.writeValueAsString(motorcycles));
    }
}


Guess what this will print:

{
  "id":1,"name":"Motorization","parentCategory":{
    "present":false
  } 
{
  "id":2,"name":"Cars","parentCategory":{
  "present":true
} 
{
  "id":3,"name":"Motorcycles","parentCategory":{
    "present":true
} 


I don’t know about you, but to me, information about whether parentCategory is present or not is not enough, and I would rather know what a parentCategory is exactly.

Jackson internally looks for getters to find class properties. The Optional class has the method isPresent(), from which Jackson makes a JSON field “present”. The value field has no standard getter, so Jackson does not include it in the JSON object.

But we can change this! Just by adding one more class:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
final class OptionalMixin {
    private OptionalMixin() {}

    @JsonProperty
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object value;
}


And call one method on our ObjectMapper instance:

... 
objectMapper.addMixIn(Optional.class, OptionalMixin.class); 
...


After this, our main method will print:

{
  "id":1,"name":"Motorization","parentCategory":{
    "present":false
} 
{
    "id":2,"name":"Cars","parentCategory":{
        "value":{
            "id":1,"name":"Motorization","parentCategory":{
		"present":false
		},
	"present":true
} 
{
  "id":3,"name":"Motorcycles","parentCategory":{
    "value":{
      "id":1,"name":"Motorization","parentCategory":{
        "present":false
      },"present":true
} 


So, this would be all for now. Summarizing, we saw a quick way to improve mapping Optionals to JSON objects. Of course, this can be used for changing mappings for more than Optional classes as well.

For the curious, the solution I’ve chosen in this domain could look like this:

package com.krzysztofgadomski.jacksonobjectmapperwithoptionals;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Optional;

class Category {
    private final int id;
    private final String name;
    @JsonProperty("parentCategory")
    private final Category parentCategory;

    Category(int id, String name, Category parentCategory) {
        this.id = id;
        this.name = name;
        this.parentCategory = parentCategory;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @JsonIgnore
    public Optional<Category> getParentCategory() {
        return Optional.ofNullable(parentCategory);
    }
}


There are quite a few benefits from POJO like this one above:

  • We do not pass Optional in a constructor and do not have it as a class field.
  • We do not have to write additional classes like OptionalMixin.
  • We can fully benefit from using Optional because getParentCategory()'s return type is still Optional
  • We have better a JSON object field parentCategory without any wrappers. The JSON objects look like this:
{
    "id":1,"name":"Motorization","parentCategory":null
}
{
    "id":2,"name":"Cars","parentCategory":
    {
        "id":1,"name":"Motorization","parentCategory":null
    }
}
{
  "id":3,"name":"Motorcycles","parentCategory":{
      "id":1,"name":"Motorization","parentCategory":null
  }
}


Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,jackson ,json ,optional ,tutorial

Published at DZone with permission of Krzysztof Gadomski. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}