【问题标题】:Java Springboot: Return only some attributs of an objectJava Spring Boot:仅返回对象的某些属性
【发布时间】:2020-01-14 12:18:18
【问题描述】:

假设以下类:

public class Foo {
  String a, b, c, d;

  // The rest of the class...
}

还有一个使用 Springboot 的 REST API 控制器:

@GetMapping("/foo")
public Foo myFuntion() {
    return new Foo(...);
}

请求/foo 返回此 JSON:

{
 "a": "...",
 "b": "...",
 "c": "...",
 "d": "..."
}

但是,我想只返回Foo 类的一些属性,例如,只返回属性ab

如果不创建新类,我怎么能做到这一点?

【问题讨论】:

  • 解决这个问题的惯用方法是创建 DTO(数据传输对象)。 Java 不太喜欢“有时是这些值,有时不是”,因为它会导致 API 不一致并破坏强类型。
  • @Christopher 如果我总是只想返回 a 和 b,那会改变吗?
  • 在您现有的 DTO 类中,使用“@JsonInclude(JsonInclude.Include.NON_EMPTY)”注释该类,然后在返回之前将 foo 的属性设置为 null。
  • 您可以查看 GraphQL,您可以在其中定义应该返回的确切内容。
  • 如果您不想返回给定的属性,请使用@JsonIgnore。如果您需要在不同的地方返回不同的属性集,请使用DTOs。

标签: java rest spring-boot


【解决方案1】:

你有两个解决方案

对要排除的属性使用@JsonIgnore

例如,您想从序列化中排除 a。(只想获取 b,c,d

public class TestDto {

@JsonIgnore
String a;
String b;
String c;
String d;
//Getter and Setter
}

使用@JsonInclude 和@JsonIgnoreProperties

通过此解决方案,如果 a、b、c、d 中的每一个都为 null,则它将被排除在响应之外。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestDto {


String a;
String b;
String c;
String d;

//getters and setter

}

More information about Jackson annotations

【讨论】:

    【解决方案2】:

    你有很多选择

    1. 使用专用 DTO - 单独的类,只包含您需要的道具
    2. 使用@JsonIgnore
    3. 使用@JsonView

    ...还有更多。我个人对第三种选择很满意 https://www.baeldung.com/jackson-json-view-annotation - 但最直接且独立于实现的是选项 1 - 所以你也可以选择它。

    【讨论】:

      【解决方案3】:

      @JsonView 将是以受控方式处理所有属性的最佳选择。

      定义视图

      public class Views {
          public static class Public {
          }
      
          public static class private {
          }
      }
      

      地图属性

      @JsonView(Views.Public.class)
      public String a;
      

      并标记返回视图

      @JsonView(Views.Public.class)
      @RequestMapping("/items/{id}")
      public Item getItemPublic(@PathVariable int id) {
          return ItemManager.getById(id);
      }
      

      现在将返回所有标有视图名称的属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-17
        • 1970-01-01
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 2021-01-17
        相关资源
        最近更新 更多