我有以下控制器从数据库中返回项目列表:
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public Page<Movies> getAll(Pageable pageable) {
return this.service.getAll(pageable);
}
正如预期的那样,Spring Boot 正确地序列化了它:
{
"content": [ ... ],
"pageable": { ... },
"last": false,
"totalPages": 2,
"totalElements": 35,
"size": 20,
"number": 0,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 20,
"first": true,
"empty": false
}
但是,我想重命名这些属性之一。例如,我想使用items
而不是content
作为键名。
在这种情况下,由于Page
is from org.springframework.data.domain
,我不能使用 Jackson 注释来重命名该属性。
我可以编写一个自定义序列化程序(类似这样),但我只想重命名该属性,所以我不想从头开始编写它。
处理这个问题的更好方法是什么?
您可以为此使用 Mix-ins。您需要一个接口或抽象类来将更改应用于不可修改的类:
interface MixIn<T> {
@JsonProperty("items")
List<T> getContent(); // rename property
}
然后注册 Mix-in:
mapper.addMixIn(Slice.class, MixIn.class);
Slice
是content
属性所在的实际类。它会产生类似的东西:
{
"last":true,
"totalElements":1,
"totalPages":1,
"size":0,
"number":0,
"numberOfElements":1,
"first":true,
"sort":null,
"items":[
"listItem"
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句