【问题标题】:How to serialize Annotation with Jackson如何用 Jackson 序列化 Annotation
【发布时间】:2016-06-24 06:02:30
【问题描述】:
我有一个简单的注解类:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebService { // with methods}
还有一个宝珠
class Pojo {
Webservice webservice;
}
每当我尝试序列化Pojo 时,除了Webservice 字段之外的所有字段都会被序列化。
我对反序列化不感兴趣,只对序列化感兴趣。
这是杰克逊的限制吗?
【问题讨论】:
标签:
java
serialization
annotations
jackson
【解决方案1】:
一个好问题。如果您在注释类型方法上放置 @JsonProperty 注释,则序列化工作正常。这是一个例子:
@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));
}
}
输出:
{"field":"value","myAnnotation":{"a":"abc","b":123}}