【发布时间】:2020-01-21 07:49:08
【问题描述】:
我正在开发一个带有 spring boot 和 hibernate 的 rest api 项目,我想知道使用 Jackson 对 RestController 进行 json 序列化。
问题是:我使用了在无法编辑的库中定义的外部休眠实体类。这些类非常复杂,并且在我使用其余 api 返回对象时定义了很多我不感兴趣的字段。
实际上,我已经解决了使用包装类包装原始类的问题,该包装类只公开我想从控制器返回的值。
例如:
原班
class AccountEntity {
///...
public String getName() {
return this.name;
}
/// ... Lot of code here
}
包装类:
class AccountWrapper {
AccountEntity original;
public AccountWrapper(AccountEntity original) {
this.original = original;
}
public String getName() {
return this.original.getName();
}
}
并使用 Wrapper 如下
@RestController("/api/user")
public class UsersController {
@GetMapping("/")
public AccountWrapper getUser() {
AccountEntity account = //get account in some way
AccountWrapper accountWrapper = new AccountWrapper(account);
return accountWrapper;
}
}
该方法效果很好,但它不是很干净并且使事情变得更复杂(例如,当我必须返回列表时),因为我总是必须包装原始类。
我没有找到一种方法让我能够指定要序列化哪些字段而不修改(我不能)原始类。
有什么帮助吗?
【问题讨论】:
-
一般您可以使用
MixIn功能并为您无法更改的外部类定义注释。看看:Jackson parse json with unwraping root, but without ability to set @JsonRootName,Jackson conditional @JsonUnwrapped
标签: java rest spring-boot jackson