我有两个端点返回这个Json:
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
我需要让它忽略第一个端点的desc并让它用于第二个端点,除了创建另一个ResponseDTO之外,还有其他解决方案吗?@jsonIgnore
将忽略所有端点的属性。
对于第一个端点:no desc
"type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}
For second: with desc
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
@JsonInclude(Include.NON_EMPTY)
应该可以做到。
包括。NON_EMPTY:表示JSON中只包含非空的属性。
最简单的解决方案,
并
public class Root {
public Type type;
//Todo getter setter constructor
}
Type.java
public class Type {
public int nbrCurrentRemainingDays;
@JsonInclude(Include.NON_EMPTY)
public String desc;
public int id;
//Todo getter setter constructor
}
MyController.java
@RestController
public class MyController {
@GetMapping("/all-fields")
public Root test1() {
Root root = new Root();
Type type = new Type();
type.setNbrCurrentRemainingDays(0);
type.setId(32);
type.setDesc("put desc here !");
root.setType(type);
return root;
}
@GetMapping("/ignore-desc")
public Root test2() {
Root root = new Root();
Type type = new Type();
type.setNbrCurrentRemainingDays(0);
type.setId(32);
type.setDesc("put desc here !");
root.setType(type);
//Set null value
type.setDesc(null);
return root;
}
}
Endpoint 1:localhost:8080/all-fields(with desc)
{
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
}
Endpoint 2: localhost:8080/ignore-desc(no desc)
{
"type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}
}
为字段使用@JsonIgnore注释,并为desc字段创建手动getter和setter,其中setter将根据字段值返回。
setter, Getter方法需要用@JsonProperty注释,现在setter将根据URL路径返回值(或根据您的选择的任何条件)。
我知道一个解决方案。您可以扩展Json Serializer类并覆盖其中的serialize方法。您可以禁用不需要的字段。就像这样
JsonView