Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure Jackson to serialize base classes first?

Tags:

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?

like image 901
Michael Avatar asked Aug 20 '19 09:08

Michael


People also ask

Does Jackson use serializable?

Introduction of ObjectMapper Class jackson. databind package and can serialize and deserialize two types of objects: Plain Old Java Objects (POJOs)

What is Jackson object serialization?

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.

Does Jackson serialize getters?

Jackson by default uses the getters for serializing and setters for deserializing.


1 Answers

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.

like image 79
Manos Nikolaidis Avatar answered Nov 15 '22 05:11

Manos Nikolaidis