与杰克逊映射注释

时间:2014-06-02 06:48:39

标签: java json serialization jackson

我正在尝试使用Jackson lib将一些注释映射到休息响应

@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.TYPE )
public @interface LogicModule
{
    String id();
    int numberOfInputs();
}

我将这些对象转换为JSON的代码是

...
final List<LogicModule> result = new LinkedList<>();
for (final Class<?> annotatedClass : annotated)
{
   final LogicModule moduleInfo = annotatedClass.getAnnotation( LogicModule.class );
   result.add(moduleInfo);
}
return Response.ok( result ).build();

不幸的是,这会返回一个空列表。我如何更改代码以使事情按预期工作?

1 个答案:

答案 0 :(得分:0)

我认为您有两个选择:使用@JsonProperty注释标记注释类型的方法,或配置将所有注释类型方法视为普通属性的自定义AnnotationIntrospector

以下示例显示了两者:

public class JacksonAnnotation {

    @Retention( RetentionPolicy.RUNTIME )
    @Target( ElementType.TYPE )
    public static @interface LogicModule {
        @JsonProperty
        String id();
        @JsonProperty
        int numberOfInputs();
    }

    @Retention( RetentionPolicy.RUNTIME )
    @Target( ElementType.TYPE )
    public static @interface LogicModule2 {
        String id();
        int numberOfInputs();
    }

    @LogicModule(id = "id", numberOfInputs = 123)
    public static class AnnotatedClass {

    }
    @LogicModule2(id = "id2", numberOfInputs = 321)
    public static class AnnotatedClass2 {

    }

    public static void main(String[] args) throws JsonProcessingException {
        List<LogicModule> modules = singletonList(AnnotatedClass.class.getAnnotation(LogicModule.class));
        List<LogicModule2> modules2 = singletonList(AnnotatedClass2.class.getAnnotation(LogicModule2.class));

        ObjectMapper mapper1 = new ObjectMapper();
        System.out.println(mapper1.writerWithDefaultPrettyPrinter().writeValueAsString(modules));

        ObjectMapper mapper2 = new ObjectMapper();
        mapper2.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
            @Override
            public PropertyName findNameForSerialization(Annotated a) {
                if (a instanceof AnnotatedMethod) {
                    Class<?> declaringClass = ((AnnotatedMethod) a).getMember().getDeclaringClass();
                    // checks that this is an annotation method
                    if (Annotation.class.isAssignableFrom(declaringClass)) {
                        try {
                            // exclude the other method defined in the super interface
                            Annotation.class.getMethod(a.getName());
                        } catch (NoSuchMethodException e) {
                            return new PropertyName(a.getName());
                        }
                    }
                }
                return super.findNameForSerialization(a);
            }
        });
        System.out.println(mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(modules2));
    }
}

输出:

[ {
  "id" : "id",
  "numberOfInputs" : 123
} ]
[ {
  "id" : "id2",
  "numberOfInputs" : 321
} ]