Micronaut Mastery: Decode JSON Using Custom Constructor Without Jackson Annotations

Micronaut uses Jackson to encode objects to JSON and decode JSON to objects. Micronaut adds a Jackson ObjectMapper bean to the application context with all configuration to work properly. Jackson can by default populate an object with values from JSON as the class has a no argument constructor and the properties can be accessed. But if our class doesn’t have a no argument constructor we need to use the @JsonCreator and @JsonProperty annotations to help Jackson. We can use these annotation on the constructor with arguments that is used to create an object.

But we can even make it work without the extra annotations, so our classes are easier to read and better reusable. We need to add the Jackson ParameterNamesModule as module to the ObjectMapper instance in our application. And we need to compile our sources with the -parameter argument, so the argument names are preserved in the compiled code. Luckily the -parameter option is already added to our Gradle build when we create a Micronaut application. All we have to do is to add the ParameterNamesModule in our application.

We need to add a dependency on com.fasterxml.jackson.module:jackson-module-parameter-names to our compile class path. Micronaut will automatically find the ParameterNamesModule and add it to the ObjectMapper using the findAndRegisterModules method.

So we change our build.gradle file first:

In our application we have the following class that has an argument constructor to create a immutable object:

We write the following sample controller to use the Language class as a return type (we wrap it in a Mono object so the method is reactive):

And in our test we use HttpClient to invoke the controller method. The exchange method will trigger a decode of the JSON output of the controller to a Language object:

When we wouldn’t have the dependency on jackson-module-parameter-names and not use the -parameter compiler option we get the following error message:

But with the dependency and -parameter compiler option we have a valid test without any errors. Jackson knows how to use the argument constructor to create a new Language object.

Written with Micronaut 1.0.0.M4.

Original post

This entry was posted in Coding, Micronaut and tagged , , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *