JsonProperty
isn't overriding the default name jackson gets from the getter. If I serialize the class below with ObjectMapper
and jackson I get
{"hi":"hello"}
As you can see the JsonProperty annotation has no effect
class JacksonTester { String hi; @JsonProperty("hello") public String getHi() { return hi; } }
Putting @JsonProperty
on the String itself doesn't work either. The only way it seems that I can change the name is by renaming the getter, the only problem is that it then will always be lowercase for the first letter
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.
You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using.
The problem was that I was using both the old and new jackson libraries
i.e. before I had import org.codehaus.jackson.annotate.JsonProperty;
Which I had to change to below, to be consistent with the library I was using.
Since I was using maven that also meant updating my maven dependencies. import com.fasterxml.jackson.annotation.JsonProperty;
For it to work, I needed the @JsonProperty
annotation on the getter (putting it on the object didn't work)
I found the answer here (thanks to francescoforesti) @JsonProperty not working as expected
If using Kotlin
I understand the original question is in Java, but since Kotlin is becoming very popular and many might be using it I'd like to post this here to help others.
Anyway, for Kotlin, because how getters/setters work, if you are using val
, meaning you only expose the getter, you may need to apply the annotation to the getter like below:
class JacksonTester(@get:JsonProperty("hello") val hi: String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With