use*_*576 5 java serialization json jackson
我使用Jackson 2.2.3将POJO序列化为JSON。然后我遇到了一个问题,就是我无法序列化递归结构...我通过使用@JsonIdentityInfo=> 解决了这个问题,效果很好。
但是,我不希望此注释位于POJO的顶部。
所以我的问题是:还有其他可能性设置我的默认行为ObjectMapper以对每个POJO使用该功能吗?
所以我想转换这个注释代码
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
Run Code Online (Sandbox Code Playgroud)
像
ObjectMapper om = new ObjectMapper();
om.setDefaultIdentityInfo(ObjectIdGenerators.IntSequenceGenerator.class, "@id");
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
您可以使用Jackson混合注释或Jackson注释内省器来实现。
这是显示两种方法的示例:
public class JacksonJsonIdentityInfo {
@JsonIdentityInfo(
generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
static class Bean {
public final String field;
public Bean(final String field) {this.field = field;}
}
static class Bean2 {
public final String field2;
public Bean2(final String field2) {this.field2 = field2;}
}
@JsonIdentityInfo(
generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id2")
static interface Bean2MixIn {
}
static class Bean3 {
public final String field3;
public Bean3(final String field3) {this.field3 = field3;}
}
static class MyJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public ObjectIdInfo findObjectIdInfo(final Annotated ann) {
if (ann.getRawType() == Bean3.class) {
return new ObjectIdInfo(
PropertyName.construct("@id3", null),
null,
ObjectIdGenerators.IntSequenceGenerator.class,
null);
}
return super.findObjectIdInfo(ann);
}
}
public static void main(String[] args) throws JsonProcessingException {
final Bean bean = new Bean("value");
final Bean2 bean2 = new Bean2("value2");
final Bean3 bean3 = new Bean3("value3");
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Bean2.class, Bean2MixIn.class);
mapper.setAnnotationIntrospector(new MyJacksonAnnotationIntrospector());
System.out.println(mapper.writeValueAsString(bean));
System.out.println(mapper.writeValueAsString(bean2));
System.out.println(mapper.writeValueAsString(bean3));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"@id":1,"field":"value"}
{"@id2":1,"field2":"value2"}
{"@id3":1,"field3":"value3"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1964 次 |
| 最近记录: |