当 Java 类的 Jackson PropertyNamingStrategy 由 @JsonNaming 显式设置时,我如何内省它?



我有一些代码从数据库中读取行,并使用Jackson ObjectMapper将它们转换为对象。我正试图使这个尽可能通用,作为一个库函数。

对于某些特定的对象类,PropertyNamingStrategy是通过@JsonNaming注释显式地设置为与我的行模式定义不同的东西(只是名称大小写不同,概念上名称和数据是相同的)。

我可以使用中间库将预期的属性名称从行模式转换为@JsonNaming注释定义它们的方式。但这是非常特定于一个类的。

是否有一种方法,我可以内省一个类类型,找出它的PropertyNamingStrategy是什么?或者在进行实际的反序列化之前,使用objectmapppper(或其他Jackson实用程序)来找出答案?这样我的调用者在使用我的代码时就不需要知道或关心这个了。

是否有一种方法可以内省类类型以找出它的PropertyNamingStrategy吗?

是的,您可以使用返回BeanDescriptionSerializationConfig#introspectClassAnnotations方法,获取其信息并创建将由JacksonAnnotationIntrospector实例检查的AnnotatedClass,如下所示:


@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
public class MyClass {}
AnnotatedClass acl = mapper.getSerializationConfig()
.introspectClassAnnotations(MyClass.class)
.getClassInfo();
JacksonAnnotationIntrospector jai = new JacksonAnnotationIntrospector();
//in this case it will prints class
//com.fasterxml.jackson.databind.PropertyNamingStrategy$KebabCaseStrategy
//In case of no annotation over the class the value will be null
System.out.println(jai.findNamingStrategy(acl));

相关内容

最新更新