[英]How to ignore Jackson annotations?
I've got two classes: 我有两节课:
public class Bar {
private String identifier;
private String otherStuff;
public Bar(){}
public Bar(String identifier, String otherStuff) {
this.identifier = identifier;
this.otherStuff = otherStuff;
}
// Getters and Setters
}
and 和
public class Foo {
private String foo;
@JsonSerialize(using=BarsMapSerializer.class)
@JsonDeserialize(using=BarsMapDeserializer.class)
private Map<String, Bar> barsMap;
public Foo(){}
public Foo(String foo, Map<String, Bar> barsMap) {
this.foo = foo;
this.barsMap = barsMap;
}
// Getters and Setters
}
When I sserialize Foo with code: 当我用代码对Foo进行sserialize时:
public static void main(String[] args) throws Exception {
Map<String, Bar> barsMap = new LinkedHashMap<>();
barsMap.put("b1", new Bar("bar1", "nevermind1"));
barsMap.put("b2", new Bar("bar2", "nevermind2"));
barsMap.put("b3", new Bar("bar3", "nevermind3"));
Foo foo = new Foo("foo", barsMap);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(foo);
System.out.println(jsonString);
}
the otput is: 输出是:
{"foo":"foo","barsMap":{"b1":"bar1","b2":"bar2","b3":"bar3"}}
For most cases it's ok, but in some cases I want to have full Bar object in my json, like bellow: 对于大多数情况来说没问题,但在某些情况下我希望在我的json中有完整的Bar对象,如下:
{"foo":"foo","barsMap":{"b1":{"identifier":"bar1", "otherStuff":"nevermind1"},"b2":{"identifier":"bar2", "otherStuff":"nevermind2"},"b3":{"identifier":"bar3", "otherStuff":nevermind3"}}}
Is it possible to achieve this without writing custom serializer? 是否可以在不编写自定义序列化器的情况下实现此目的 I know that I can add annotation using mix-in mechanism, but basically I need to ignore existing one in some cases. 我知道我可以使用混合机制添加注释,但基本上我需要在某些情况下忽略现有的注释。
I've resolved my problem using mix-in mechanism. 我已经使用混合机制解决了我的问题。
public interface FooMixin {
@JsonSerialize
Map<String, Bar> getBarsMap();
@JsonDeserialize
void setBarsMap(Map<String, Bar> barsMap);
}
With this interface mixed in, class Foo
is serialized as with default serializer. 混合使用此接口后,类Foo
被序列化为默认序列化程序。 As You can see You need to add JsonSerialize
/ JsonDeserialize
annotations without specify any class. 如您所见,您需要添加JsonSerialize
/ JsonDeserialize
注释而不指定任何类。
Below code shows usage of this interface: 下面的代码显示了此接口的用法:
mapper = new ObjectMapper();
mapper.addMixInAnnotations(Foo.class, FooMixin.class);
jsonString = mapper.writeValueAsString(foo);
System.out.println(jsonString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.