Skip to content
Advertisement

How to deserialize JSON with @JsonCreator and @JsonGetter

I have the JSON looks like the following:

JavaScript

and I have a class Person:

JavaScript

I need to deserialize and serialize it, but when I’m trying to deserialize this JSON I get unexpected result.

JavaScript

Why when I’m trying to deserialize it the @JsonGetter annotation is used for it?
How can I disable @JsonGetter annotation when I try to deserialize the JSON?

Advertisement

Answer

If @JsonGetter is used as is currently, it will map property n_age to field age. To citate the docsIt can be used as an alternative to more general JsonProperty annotation (which is the recommended choice in general case).

To fix this behaviour, you need to:

  1. Tell jackson to ignore property n_age, otherwise you will get exception for unrecognized property not marked as ignorable – @JsonIgnoreProperties("n_age").
  2. Tell jackson to allow getters for ignored properties(basically make it readonly) – @JsonIgnoreProperties(value = {"n_age"}, allowGetters = true)

In the end, Person should look like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement