java - 将 Jackson 配置为忽略除类字段/成员之外的所有内容
问题描述
我有一个 Spring Boot 2.3.2.RELEASE
WebFlux 应用程序。我有一些 JPA 实体作为 RESTful API 响应的一部分返回。
问题是,当我向这些 JPA 实体添加方法(暴露行为)时,这些返回类型/值也被发回,我想避免这种情况。
基本上,我正在寻找的是配置 Jackson 以仅(反)序列化类字段/成员和任何用@JsonProperty
. 我也可以采用默认忽略所有内容的方法,并将其@JsonProperty
放在我想要(反)序列化的成员上。
另请注意:
这些类没有设置器,并且通常没有构造函数(除了所需的无参数之一)。他们大部分时间都使用建筑商。
我知道我可以只用 注释这些方法
@JsonIgnore
,但是会有很多这样的方法,所以我想知道是否有另一种解决方案只包括(类的)字段/成员和任何用@JsonProperty
.
解决方案
可能性取决于您拥有的实际代码,但您可以检查visibility。你可以配置你ObjectMapper
喜欢的:
om.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
om.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
然后像下面的类序列化将按照评论中的说明进行:
public static class TestClass {
@Getter // getter is generated but ignored
// because visibility for GETTER is NONE
// still serialized because visibility for FIELD is ANY
private String fieldThatShouldBeSerialized = "It is OK to serialize me :)";
// not serialized because visibility for GETTER is NONE
public String getMethodThatShouldNotBeSerialized() {
return "It is NOT OK to serialize me :(";
}
@JsonProperty // serialized because explicitly asked (not auto)
public String methodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
@JsonProperty // serialized because explicitly asked (not auto)
// even it is a "getter"
public String getAnotherMethodThatShouldBeSerialized() {
return "It is OK to serialize me also :)";
}
}
推荐阅读
- javascript - Service Worker 正在抓住一切
- python - 来自参考日期的历史日期的日期列表
- html - Text-To-Speech 软件可以读取 HTML 注释吗?
- javascript - 返回多个站点的 HTTP 状态码
- python - 如何创建一个函数来动态创建一个范围内的元组列表?
- reactjs - 使用 react 和 express 设置 nginx
- optaplanner - Optaplanner ConstraintsStream 用负整数惩罚
- python - Python找不到正确的Mysqlclient
- javascript - Javascript:使用按钮 Onclick 函数创建多个 Li 项目
- artificial-intelligence - 人工智能一种现代方法 - 随时间推移的概率推理