Using Jackson, how can I get a list of known JSON properties for any arbitrary pojo class?

Ideally, it would look like this:

List<String> props = objectMapper.getKnownProperties(MyPojo.class); 

Alas, there is no such method. The approach that usually works is to explicitly set Include.ALWAYS as the default ObjectMapper, instantly instantiate the class, convert it to a map, and examine the key set. However, classes can still override ObjectMapper, including the behavior given by the annotation.

Is there a more elegant approach? At least is there a way to override class annotations using the mapper object?

Edit:
To clarify, these pojos / javabeans / DTO are intended for use with Jackson and are already compiled with annotations to lead to a certain serialization. It just so happens that I need to dynamically know how I can be at the forefront, ideally, without duplicating the information already available to Jackson. However, if another framework offers this functionality, I would be interested to know. :)

+3
source share
4 answers

With Jackson, you can learn the class and get the available JSON properties using:

 // Construct a Jackson JavaType for your class JavaType javaType = mapper.getTypeFactory().constructType(MyDto.class); // Introspect the given type BeanDescription beanDescription = mapper.getSerializationConfig().introspect(javaType); // Find properties List<BeanPropertyDefinition> properties = beanDescription.findProperties(); 

If you have @JsonIgnoreProperties class level annotations check this answer .

+3
source

Depending on your specific needs, JsonFilter may also work (f.ex see http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html ).

And for more complex cases, the BeanSerializerModifier gives you access to the actual list of BeanPropertyWriter s, which are separate POJO properties. From this, you can write a shell that allows / disables output dynamically. Or, perhaps you can combine the approaches: a modifier to get a list of possible property names; then FilterProvider to add the filter dynamically. The advantage of this would be that it is a very efficient way to implement filtering.

+2
source

You can ignore all annotations using the dummy AnnotationIntrospector:

 objectMapper.setAnnotationIntrospector(new AnnotationIntrospector(){ @Override public Version version() { return Version.unknownVersion(); } }); 
+1
source

Perhaps you could use the Jackson JSON Schema module to create a schema for the class, and then check the schema.

+1
source

Source: https://habr.com/ru/post/1502873/


All Articles