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

标签 java json spring jackson jackson-databind

我有两个返回此 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/

相关文章:

java - Ant:无法创建任务或输入 javac

java - 如何为类(class)生成随机数?

java - reactor-netty:使用 keep-alive HTTP 客户端

java - 在 ORMLite queryRaw 方法中获取两个日期字符串之间的日期时出现 SQLException

java - 在单独的类中加载 JSON 数组列表并在另一个 Activity 中加载

c# - ASP.NET Web Api - 使用分块传输编码时,框架不会将 JSON 转换为对象

java - Kafka Streams 在多个流中拆分 1 个流

java - Spring集成单元测试http :outbound-gateway

Spring boot starter parent 2.0.0 未找到依赖项

java - 使用 Spring + Thymeleaf 时出现 java.lang.StackOverflowError