17

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

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;
}
4

2 回答 2

26

使用@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");
    }
}
于 2012-10-17T08:36:14.523 回答
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;
}

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

于 2012-10-16T19:46:37.170 回答