gpt4 book ai didi

java - 如何仅针对给定的单个端点忽略 JsonProperty 并让它适用于其他端点

转载 作者:行者123 更新时间:2023-12-05 05:42:57 26 4
gpt4 key购买 nike

我有两个返回此 Json 的端点:

 "type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}

我需要让它忽略第一个端点的 desc 而让它忽略第二个端点,除了创建另一个 ResponseDTO 之外还有其他解决方案吗?@jsonIgnore 将忽略所有端点的属性。


对于第一个端点:无描述

 "type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}

对于第二个:使用 desc

"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}

最佳答案

@JsonInclude(Include.NON_EMPTY) 应该可以解决问题。

Include.NON_EMPTY:表示只有不为空的属性才会包含在JSON中。

最简单的解决方案,

根.java

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;
}
}

端点 1:localhost:8080/all-fields(with desc)

  {
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
}

端点 2:localhost:8080/ignore-desc(no desc)

  {
"type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}
}

关于java - 如何仅针对给定的单个端点忽略 JsonProperty 并让它适用于其他端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71918764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com