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

前端 未结 4 1271
暖寄归人
暖寄归人 2020-12-20 18:40

Ideally, it would look much like this:

List props = objectMapper.getKnownProperties(MyPojo.class);

Alas, there is no such met

相关标签:
4条回答
  • 2020-12-20 19:10

    It's possible to ignore all annotations by using a dummy AnnotationIntrospector:

    objectMapper.setAnnotationIntrospector(new AnnotationIntrospector(){
        @Override public Version version() {
            return Version.unknownVersion();
        }
    });
    
    0 讨论(0)
  • 2020-12-20 19:11

    With Jackson, you can introspect a 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.

    0 讨论(0)
  • 2020-12-20 19:14

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

    And for more advanced cases, BeanSerializerModifier does give you access to actual list of BeanPropertyWriters, which represent individual properties POJO has. From that, you could write a wrapper that enables/disables output dynamically. Or perhaps you can even combine approaches: modifier to get list of possible property names; then FilterProvider to dynamically add filter. Benefit of this would be that it is a very efficient way of implementing filtering.

    0 讨论(0)
  • 2020-12-20 19:25

    Perhaps you could use Jackson's JSON Schema module to generate a schema for a class, then inspect the schema.

    0 讨论(0)
提交回复
热议问题