Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

A project needs to use the following combinaison of Jackson annotations together a lot. So, is there a way to create another annotation to avoid ugly copy/paste:

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

Update: I've tried this, without success :-(

@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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

The use of @JacksonAnnotationsInside solve the problem:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...