创建自定义 Jackson 注释 [英] Create a custom Jackson annotation

查看:47
本文介绍了创建自定义 Jackson 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

这篇关于创建自定义 Jackson 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆