如何使用jackson获取基于json属性名称的reader方法?

时间:2016-12-24 17:54:21

标签: java json jackson

鉴于以下杰克逊注释类:

public class AClass {

   @JsonProperty("propertyName")
   private String anyProperty

   public String getAnyProperty() {
   ...
   }

...
}

或mixin配置:

public class AClass {

   private String anyProperty

   public String getAnyProperty() {
   ...
   }

...
}

public interface AClassMixin {

   @JsonProperty(value = "propertyName")
  String getAnyProperty();
}

如何获取json属性" propertyName'读者方法使用杰克逊?

我需要这样的东西:

   ObjectMapper mapper = new ObjectMapper();

   Method method = mapper.getReaderMethodForProperty("propertyName", Aclass.class);

1 个答案:

答案 0 :(得分:2)

为您的bean类构建JavaType

JavaType target = objectMapper.constructType(AClass.class);

然后使用ObjectMapper' s DeserializationConfig来反省它。这将为您提供BeanDescription

BeanDescription beanDescription = objectMapper.getDeserializationConfig().introspect(target)

您可以使用它来获取其BeanPropertyDefinition个实例的列表。

List<BeanPropertyDefinition> beanPropertyDefinitions = beanDescription.findProperties();

每个BeanPropertyDefinition都有检索getter和setter(以及其他内容)作为AnnotatedMember值的方法,您可以从中检索Member(您需要转换为{ {1}})。

Method