I have some JSON schemas which exist in a hierarchy: A extends B extends C. I am generating Java classes from these using jsonschema2pojo and they get generated into a matching class hierarchy.
Because of the way I am generating the classes, I don't have fine-grained control of which annotations can be applied to which fields (i.e. @JsonPropertyOrder
)
When I serialize with Jackson, I get something like
{
"propertyOfA": "razz",
"propertyOfA": "jazz",
"propertyOfA": "baz",
"propertyOfB": "bar",
"propertyOfC": "foo"
}
Which is correct since property order has no meaning in JSON. However, my actual messages are very long - thousands of characters - and when browsing the logs it would be much more convenient if the more generic attributes (those from the base schema, schema C), of which there are only a few, came first in the message.
The individual property order within a schema/class doesn't bother me so much, but it would be nice if I could get Jackson to descend the hierarchy first and then backtrack.
{
"propertyOfC": "foo",
"propertyOfB": "bar",
"propertyOfA": "razz",
"propertyOfA": "jazz",
"propertyOfA": "baz"
}
I checked all of the Feature
s and MapperFeature
s and the only thing I found to influence the order was SORT_PROPERTIES_ALPHABETICALLY
.
Is there anything else I can do at the ObjectMapper
-level, or otherwise without changing the class, to influence this order?
Introduction of ObjectMapper Class jackson. databind package and can serialize and deserialize two types of objects: Plain Old Java Objects (POJOs)
Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.
Jackson by default uses the getters for serializing and setters for deserializing.
You can apply mixin annotations on a class outside of its (generated) source file. E.g.
on a new file, define an interface:
@JsonPropertyOrder({"propertyOfC", "propertyOfB"})
public interface MixinA {
}
and register it with your ObjectMapper
:
objectMapper.addMixIn(A.class, MixinA.class);
properties listed in this order annotation go first so you may skip properties of A.
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