简体   繁体   English

如何使用Jackson序列化注释

[英]How to serialize Annotation with Jackson

I have a simple annotation class: 我有一个简单的注释类:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebService { // with methods}

And a pojo 和一个pojo

class Pojo {
    Webservice webservice;
}

Whenever I try to serialize Pojo , all the fields get serialized except the Webservice field. 每当我尝试序列化Pojo ,除Webservice字段外,所有字段都将被序列化。

I'm not interested in deserializing, only serialization. 我对反序列化不感兴趣,仅对序列化感兴趣。

Is that a restriction in Jackson ? 那是杰克逊的限制吗?

A good question. 一个好问题。 Serialization works fine if you put a @JsonProperty annotation on your annotation type methods. 如果将@JsonProperty批注放在批注类型方法上,则序列化效果很好。 Here is an example: 这是一个例子:

@JacksonAnnotationSerialization.MyAnnotation(a = "abc", b = 123)
public class JacksonAnnotationSerialization {

    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation {
        @JsonProperty
        String a();
        @JsonProperty
        int b();
    }

    static class Thing {
        public final String field;
        public final MyAnnotation myAnnotation;

        Thing(final String field, final MyAnnotation myAnnotation) {
            this.field = field;
            this.myAnnotation = myAnnotation;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        final MyAnnotation annotation
                = JacksonAnnotationSerialization.class.getAnnotation(MyAnnotation.class);
        final Thing thing = new Thing("value", annotation);
        System.out.println(objectMapper.writeValueAsString(thing));
    }
}

Output: 输出:

{"field":"value","myAnnotation":{"a":"abc","b":123}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM