Create a custom Jackson annotation

后端 未结 2 1563
天命终不由人
天命终不由人 2020-12-08 11:45

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:

<         


        
相关标签:
2条回答
  • 2020-12-08 12:21

    I would guess that you could write your own annotation classes

    package org.codehaus.jackson.annotate ;
    
    public @ interface JsonProperty
    {
          String value ( ) default "_id" ;
    }
    
    public @ interface JsonSerialize
    {
          Class using ( ) default IdSerializer.class ;
    }
    
    ...
    

    Compile these classes and make sure that are in your classpath before the original versions. This reduces but does not eliminate the copy/paste.

    Then your code sample becomes

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

    I realize it is not really what you wanted, but it is a start.

    0 讨论(0)
  • 2020-12-08 12:23

    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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题