创建自定义杰克逊注释

2022-09-03 01:01: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;
}

答案 1

使用方法解决以下问题:@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");
    }
}

答案 2

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

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

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


推荐