Using Jackson ObjectMapper with Optionals

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

Ok, so let’s start with some code. Consider, you’re writing some e-commerce application, in which exist 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 field of a POJO class
  • we pass Optional in a constructor

As the second, can be easily fixed just by modify’ing 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.:
https://dzone.com/articles/optional-method-parameters
http://blog.jhades.org/java-8-how-to-use-optional/

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 few benefits from POJO like this one:

  • we do not pass Optional in 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() return type is still Optional
  • we have better JSON object field parrentCategorry 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}}
    

One thought on “Using Jackson ObjectMapper with Optionals

Leave a comment