Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a custom Jackson annotation

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;
}
like image 718
yves amsellem Avatar asked Oct 16 '12 19:10

yves amsellem


People also ask

Can we create custom annotation in spring boot?

In this way, we can create different custom annotations for validation purposes. You can find the full source code here. It is easy to create and use custom annotations in Java. Java developers will be relieved of redundant code by using custom annotations.

Can we create our own annotations in Java?

To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java Annotation for you. The @interface will describe the new annotation type declaration. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare some variables.


1 Answers

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");
    }
}
like image 88
yves amsellem Avatar answered Sep 22 '22 07:09

yves amsellem