使用Jackson,您可以内省一个任意类以获取可用的JSON属性:
// Construct a Jackson JavaType for your classJavaType javaType = mapper.getTypeFactory().constructType(MyDto.class);// Introspect the given typeBeanDescription beanDescription = mapper.getSerializationConfig().introspect(javaType);// Find propertiesList<BeanPropertyDefinition> properties = beanDescription.findProperties();
该
BeanPropertyDefinition列表应为您提供有关JSON属性所需的详细信息。
在
@JsonIgnoreProperties类级别的注释不考虑与上面提到的方法。但是您可以使用
AnnotationIntrospector来获取在类级别忽略的属性:
// Get class level ignored propertiesSet<String> ignoredProperties = mapper.getSerializationConfig().getAnnotationIntrospector() .findPropertyIgnorals(beanDescription.getClassInfo()).getIgnored();
然后过滤
properties除去存在于中的属性
ignoredProperties:
// Filter properties removing the class level ignored onesList<BeanPropertyDefinition> availableProperties = properties.stream() .filter(property -> !ignoredProperties.contains(property.getName())) .collect(Collectors.toList());
即使为您的班级定义了混入,此方法也有效。
该
AnnotationIntrospector#findPropertyIgnorals(Annotated)方法在Jackson
2.8中引入。该
AnnotationIntrospector#findPropertiesToIgnore(Annotated,boolean)方法可用于旧版本(但自Jackson
2.8起已弃用)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)