【问题标题】:How convert an annotation (all its diff properties) into a JSON object using Jackson/ObjectMapper?如何使用 Jackson/ObjectMapper 将注释(其所有差异属性)转换为 JSON 对象?
【发布时间】:2017-08-04 19:20:47
【问题描述】:

我有一个注解,在它运行时用于方法时,我想将它(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));

【问题讨论】:

    标签: java json annotations jackson objectmapper


    【解决方案1】:

    找到答案:

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

    例子:

    public @interface MyAnnotation {
    
        @JsonGetter(value = "name")
        String name();
    
        @JsonGetter(value = "age")
        Integer age();
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2018-11-18
      • 2016-06-13
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多