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.

Continue reading

Spicy Spring: Customize error JSON response with ErrorAttributes

The default JSON error body of Spring Boot can be customized or extended by defining our own ErrorAttributes implementation. In Spring Boot we get an error response JSON format for free. Any thrown Exception is automatically translated to this JSON format and returned with a corresponding HTTP status.

Default implementation

As soon as we throw an Exception in a @RequestMapping annotated method of a @Controller, the thrown Exception is translated to a HTTP status and a JSON error body.

The default JSON error body looks like:

Write your own ErrorAttributes implementation

What if we want extra attributes in this JSON error body?

Just define an implementation for ErrorAttributes and register it as a Spring @Component. The following example will result in a customized JSON error response body with the cause of the exception included.

Our resulting body will now look like:

Happy developing!

Groovy Goodness: Relax… Groovy Will Parse Your Wicked JSON

Since Groovy 2.3 the JSON parser has improved and is really a performant parser for JSON payload. JSON must be formatted in a strict way, for example all keys must be enclosed in double quotes. But what if we have JSON which not applies to the strict specification? For example a configuration file written in JSON and we want to add comments to this file. Or use single quotes for keys, or just leave all the quotes out. We can now specify the type JsonParseType.LAX for our JSON parser and we can now parse JSON which doesn’t apply to the strict specification.

Continue reading