我有一个简单的注释类:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebService { // with methods}
和pojo
class Pojo {
Webservice webservice;
}
每当我尝试序列化Pojo
时,除了Webservice
字段外,所有字段都会被序列化。
我对反序列化没有兴趣,只对序列化感兴趣。
这是杰克逊的限制吗?
答案 0 :(得分:0)
一个好问题。如果在注释类型方法上添加@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}}