使用Jackson,如何为任意pojo类获取已知JSON属性的列表? [英] Using Jackson, how can a list of known JSON properties be obtained for any arbitrary pojo class?
问题描述
理想情况下,它看起来很像:
Ideally, it would look much like this:
List<String> props = objectMapper.getKnownProperties(MyPojo.class);
唉,没有这样的方法。通常可行的方法是将Include.ALWAYS显式设置为ObjectMapper的默认值,反射性地实例化该类的实例,将其转换为映射,并检查键集。但是,类仍然可以覆盖给定注释的ObjectMapper的包含行为。
Alas, there is no such method. An approach that would generally work is to explicitly set Include.ALWAYS as the ObjectMapper's default, instantiate an instance of the class reflectively, convert it to a map, and examine the keyset. However, classes can still override the ObjectMapper's include behavior given annotations.
有更优雅的方法吗?至少,有没有办法使用对象映射器覆盖类注释?
Is there a more elegant approach? At the very least, is there a way to override class annotations using the object mapper?
编辑:
澄清一下,这些pojos / javabeans / DTO设计用于与Jackson一起使用,并且已经使用注释进行操作以产生特定的序列化行为。事实上,我需要动态地知道我可能会预先得到什么,最好不要重复杰克逊已有的信息。也就是说,如果另一个框架提供此功能,我很想知道。 :)
Just to clarify, these pojos/javabeans/DTOs are designed for use with Jackson and are already rigged with annotations to result in specific serialization behavior. It just so happens that I need to dynamically know what I might end up with up-front, ideally without duplicating the information already available to jackson. That said, if another framework offers this functionality, I'd be curious to know. :)
推荐答案
使用Jackson,您可以使用以下内容对类进行内省并获取可用的JSON属性:
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();
如果您有 @JsonIgnoreProperties
班级注释,检查一下< a href =https://stackoverflow.com/a/45839099/1426227>答案。
这篇关于使用Jackson,如何为任意pojo类获取已知JSON属性的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!