代码之家  ›  专栏  ›  技术社区  ›  Don Rhummy

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

  •  0
  • Don Rhummy  · 技术社区  · 9 年前

    注释:

    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));
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Don Rhummy    9 年前

    找到了答案:

    @JsonGetter 并将要表示的字段的名称传递给它。

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

    {"name":"test","age":21}