假设我有这个对象:
class Person {
String name;
Household getHousehold();
}
class Household {
Set<Address> getAddresses();
String householdId;
}
通常按如下方式序列化
{
"name": "XXX",
"household": {
"addresses": [...]
}
}
有没有办法配置杰克逊注释/混合来获得这个(即不使用DTO)?
{
"name": "XXX",
"addresses": [...],
"household": {
"householdId": 123
}
}
答案 0 :(得分:3)
您可以使用mixins和annotations配置特定属性的展开:
<强> 1。 Mixins
假设你定义了以下mixin:
public abstract class UnwrappedAddresses {
@JsonUnwrapped
public abstract Household getHouseHold();
}
然后在objectMapper中添加一个自定义模块,它将mixin应用于Person类,如下所示:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper .registerModule(new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(Person.class, UnwrappedAddresses.class);
}
});
此方法不会将“家庭”序列化更改为单个项目,而只是在将家庭项目封装在Person对象中时将其解包。
<强> 2。注释
只需将@JsonUnwrapped添加到您的getHouseHold()方法。
你想要的基本上是改变json的输出,这可以通过使用@JsonAnyGetter
注释(可以动态地向你的pojo添加新属性)来完成。
您可以通过忽略家庭财产并在@JsonAnyGetter的帮助下解开它来实现您的预期结果。
@JsonIgnoreProperties("houseHold")
public static class Person {
String name;
Household houseHold;
@JsonAnyGetter
public Map<String,Object> properties(){
Map<String,Object> additionalProps=new HashMap<>();
additionalProps.put("addresses", new ArrayList<>(houseHold.getAddresses()));
Map<String,Object> houseHolProps=new HashMap<>();
houseHolProps.put("houseHoldId", houseHold.id);
additionalProps.put("houseHold", houseHolProps);
return additionalProps;
}
..getters&setters omitted
}
序列化后返回
{"name":"name",
"houseHold":{"houseHoldId":0},
"addresses":[
{"houseNo":2,"street":"abc"},
{"houseNo":1,"street":"str"}
]
}