如何使用 Jackson/ObjectMapper 将注释(其所有差异属性)转换为 JSON 对象?

How convert an annotation (all its diff properties) into a JSON object using Jackson/ObjectMapper?

我有一个注释,在它运行时用于一个方法时,我想将它 9 及其所有 属性 值转换成一个 JSON 对象。

注解:

public @interface MyAnnotation {
    String name();
    Integer age();
}

使用情况:

public class MyClass {
    @MyAnnotation(name = "test", age = 21)
    public String getInfo()
    { ...elided... }
}

MyClass 类型的对象上使用反射并从其 getInfo 方法获取注释时,我希望能够将注释转换为 JSON。但是它没有任何字段(因为@interfaces 不能有字段),那么有没有办法配置一个 ObjectMapper 来使用这些方法作为属性呢?

//This just prints {}
new ObjectMapper().writeValueAsString(method.getAnnotation(MyAnnotation.class));

找到答案:

使用 @JsonGetter 并将您希望它表示的字段名称传递给它。

示例:

public @interface MyAnnotation {

    @JsonGetter(value = "name")
    String name();

    @JsonGetter(value = "age")
    Integer age();
}

这将输出为 json:{"name":"test","age":21}