被 @JsonAnyGetter
注解的方法必须是非静态的、无参数的,且返回值必须为 java.util.Map
。序列化时,Map 的条目会被扁平化(与对象其他的属性位于同一级别,与 @JsonUnwrapped
的处理方式相同),而不是作为嵌套属性被序列化。
Example
POJO
public class ScreenInfo {
private String id;
private String title;
private int width;
private int height;
private Map<String, Object> otherInfo;
...
@JsonAnyGetter
public Map<String, Object> getOtherInfo() {
return otherInfo;
}
public void addOtherInfo(String key, Object value) {
if (this.otherInfo == null) {
this.otherInfo = new HashMap<>();
}
this.otherInfo.put(key, value);
}
...
}
序列化
public class MainScreenInfoSerialization {
public static void main(String[] args) throws IOException {
ScreenInfo si = new ScreenInfo();
si.setId("TradeDetails");
si.setTitle("Trade Details");
si.setWidth(500);
si.setHeight(300);
si.addOtherInfo("xLocation", 400);
si.addOtherInfo("yLocation", 200);
System.out.println("-- before serialization --");
System.out.println(si);
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(si);
System.out.println("-- after serialization --");
System.out.println(jsonString);
}
}
xLocation、yLocation 被序列化成了扁平化的属性,而不是嵌套属性
-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}
不使用 @ JSONAnyGetter
xLocation、yLocation 被序列化成了嵌套属性
-- before serialization --
ScreenInfo{id='TradeDetails', title='Trade Details', width=500, height=300, otherInfo={xLocation=400, yLocation=200}}
-- after serialization --
{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"otherInfo":{"xLocation":400,"yLocation":200}}
原文链接
Jackson JSON - Using @JsonAnyGetter Annotation to serialize any arbitrary properties