Property is not serialized when both @JsonProperty and @JsonIgnore are present
I encountered a situation where a property annotated with both @JsonProperty and @JsonIgnore is not being serialized. In Jackson wiki said, that @JsonProperty:
also indicates that property is to be included
Based on this, I assumed that @JsonProperty would override @JsonIgnore. However, in the following example, the property is omitted from the serialized JSON:
public class Box {
@JsonProperty
@JsonIgnore
private int size;
public Box(int size) {
this.size = size;
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
Box box = new Box(10);
String json = objectMapper.writeValueAsString(box);
System.out.println(json);
}
}
Expected output:
{"size":10}
But got:
{}
Jackson version: 2.19.3
I used a very simple example just to demonstrate the behavior, but the same issue also occurs with subclasses.
If this behavior is expected, it would be very helpful to have documentation describing the priority of different annotations, because it is currently unclear which annotation takes precedence over others.
The annotation precedence between subclasses and interfaces is not clear either. I have opened a ticket for another confusing case: https://github.com/FasterXML/jackson-annotations/issues/306
@JsonIgnore has precedence if both present (as it seems more specific); at any rate, this works as intended.
Precedence indeed complicated across annotations: individual annotation types are flattened across hierarchy, but there is no way to compare -- like in this case -- if one would be "closer": all are known to exist for value type in question, somewhere in the hierarchy.
I'll see if I can add a note on @JsonProperty Javadocs to indicate conflict with @JsonIgnore.