How can I configure Jackson to serialize base classes first?

Michael :

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 Features and MapperFeatures 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?

Manos Nikolaidis :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139818&siteId=1