我正在使用 JHipster(spring boot) 来生成我的项目。我想在 application.yml 中隐藏/显示 JSON 中的字段。例如:
我有以下类(class)
@Entity
@Table(name = "port")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Port implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "description")
private String description;
//getters & setters
}
我的 GET 方法返回如下响应:
{
"id": 1,
"city": "boston",
"description": "test test"
}
我希望能够在 application.yml 中包含/排除某些字段(因为我没有 application.properties),否则会有类似的内容:
//application.yml
include: ['city']
exclude: ['description']
在这个例子中,我的 json 应该是这样的:
{
"id": 1,
"city": "boston",
}
例如,如果我有 40 个字段并且我需要隐藏 10 并显示 30,我只想将要隐藏的 10 放在 application.yml 中的排除中,而无需每次都更改代码。我猜@jsonignore 隐藏字段,但我不知道如何从 application.yml 中做到这一点
抱歉没有好好解释。我希望它很清楚。
提前感谢您提供类似操作的任何建议或解决方案
最佳答案
Spring boot 默认使用 Jackson JSON 库将您的类序列化为 Json。在该库中,有一个注释 @JsonIgnore
精确地用于告诉 Json 引擎从序列化/反序列化中忽略特定属性。因此,假设在您的实体 Port
中,您希望从显示中排除属性 city。您所要做的就是使用 @JsonIgnore
注释对该属性(或其 getter 方法)进行注释:
@Column(name = "city")
@JsonIgnore
private String city;
关于json - 在 application.yml 的 json 响应中包含/排除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71374764/