Search code examples
javajsonannotationsjacksonobjectmapper

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


I have an annotation and during its runtime use on a method, I want to convert it 9and all its property values) into a JSON object.

The annotation:

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

Use of it:

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

When using reflection on an object of type MyClass and getting the annotation from its getInfo method, I would like to be able to convert the annotation to JSON. But it doesn't have any fields (since @interfaces can't have fields), so is there a way to configure an ObjectMapper to use the methods as properties instead?

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

Solution

  • Found the answer:

    Use @JsonGetter and pass it the name of the field you want it to represent.

    Example:

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

    This will output as the json: {"name":"test","age":21}