Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

given a class, how to get the jackson structure of the class serialization?

Tags:

java

json

jackson

Given an arbitrary class, is it possible for Jackson to provide a list of the fields needed to serialize and deserialize it?

Jackson's serialization rules are complex. I'd like to determine at runtime what the Jackson JSON structure is expected for an arbitrary class (both serialization and deserialization). My current planned implementation is to look for an @JsonConstructor constructor method and parse its arguments. If that's not there, look for annotations on other methods, and otherwise, use the list of member variables. I'll recurse the algorithm for any non-primitive field types.

The end goal is to create documentation for service endpoints.

like image 728
Chris Casey Avatar asked Nov 22 '25 05:11

Chris Casey


1 Answers

Yes, you can use Jackson's introspection. This has the benefit that all annotations are applied as expected, and result should be exactly as Jackson "sees" the type you want information about.

There are at least two ways to do that:

  1. Request introspection via SerializationConfig (or, DeserializatonConfig), to get a BeanDescription
  2. Use callback/visitor based approach by calling ObjectMapper.acceptJsonFormatVisitor(type, visitor)

First method is usually simpler:

JavaType type = mapper.constructType(MyBean.class);
BeanDescription desc = mapper.getSerializationConfig()
   .introspect(type);

but latter is useful for tasks like generation of schemas (JSON Schema, XML Schema, protoc, thrift).

like image 120
StaxMan Avatar answered Nov 24 '25 20:11

StaxMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!