创建自定义Jackson注释

时间:2012-10-16 19:09:58

标签: java annotations marshalling jackson

项目需要结合使用以下杰克逊注释的组合。那么,有没有办法创建另一个注释来避免难看的复制/粘贴:

public class A {
    @JsonProperty("_id")
    @JsonSerialize(using=IdSerializer.class)
    @JsonDeserialize(using=IdDeserializer.class)
    String id;
}

public class B {
    @JsonProperty("_id")
    @JsonSerialize(using=IdSerializer.class)
    @JsonDeserialize(using=IdDeserializer.class)
    String id;
}

public class C {
    @CustomId // don't repeat that configuration endlessly
    String id;
}

更新:我试过这个,没有成功: - (

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonProperty("_id")
@JsonSerialize(using=IdSerializer.class, include=JsonSerialize.Inclusion.NON_NULL)
@JsonDeserialize(using=IdDeserializer.class)
public @interface Id {}

public class D {
    @Id
    private String id;
}

2 个答案:

答案 0 :(得分:20)

使用@JacksonAnnotationsInside解决问题:

public class JacksonTest {

    @Retention(RetentionPolicy.RUNTIME)
    @JacksonAnnotationsInside
    @JsonProperty("_id")
    @JsonSerialize(using=IdSerializer.class, include=Inclusion.NON_NULL)
    @JsonDeserialize(using=IdDeserializer.class)
    public @interface Id {
    }

    public static class Answer {
        @Id
        String id;
        String name;

        public Answer() {}
    }

    @Test
    public void testInside() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        VisibilityChecker<?> checker = mapper.getSerializationConfig().getDefaultVisibilityChecker();
        mapper.setVisibilityChecker(checker.withFieldVisibility(JsonAutoDetect.Visibility.ANY));

        String string = "{ 'name' : 'John' , '_id' : { 'sub' : '47cc'}}".replace('\'', '"');
        Answer answer = mapper.reader(Answer.class).readValue(string);
        Assertions.assertThat(answer.id).isEqualTo("47cc");
    }
}

答案 1 :(得分:1)

我猜你可以编写自己的注释类

package org.codehaus.jackson.annotate ;

public @ interface JsonProperty
{
      String value ( ) default "_id" ;
}

public @ interface JsonSerialize
{
      Class using ( ) default IdSerializer.class ;
}

...

编译这些类并确保它们在原始版本之前位于类路径中。这会减少但不会消除复制/粘贴。

然后您的代码示例变为

public class A {
    @JsonProperty
    @JsonSerialize
    @JsonDeserialize
    String id;
}

public class B {
    @JsonProperty
    @JsonSerialize
    @JsonDeserialize
    String id;
}

我意识到这不是你想要的,但它是一个开始。