JavaSpringBoot:只返回对象的一些属性

JavaSpringBoot:只返回对象的一些属性,java,rest,spring-boot,Java,Rest,Spring Boot,假设以下类别: 公共类Foo{ 字符串a、b、c、d; //班上其他人。。。 } 以及使用Springboot的REST API控制器: @GetMapping(“/foo”) 公共食品功能(){ 返回新的Foo(…); } 请求/foo返回此JSON: { "a": "...", "b": "...", "c": "...", "d": "..." } 但是,我只想返回Foo类的一些属性,例如,仅返回属性a和b 如果不创建新类,我怎么能做到这一点呢?您有很多选择 使用专用DTO-

假设以下类别:

公共类Foo{
字符串a、b、c、d;
//班上其他人。。。
}
以及使用Springboot的REST API控制器:

@GetMapping(“/foo”)
公共食品功能(){
返回新的Foo(…);
}
请求
/foo
返回此JSON:

{
 "a": "...",
 "b": "...",
 "c": "...",
 "d": "..."
}
但是,我只想返回
Foo
类的一些属性,例如,仅返回属性
a
b


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

您有很多选择

  • 使用专用DTO-只包含所需道具的独立类
  • 使用@JsonIgnore
  • 使用@JsonView
  • 。。。还有更多。我个人对第三种选择很满意 -但最直接和独立于实现的是选项1,所以您也可以选择它。

    您有两种解决方案

    对要排除的属性使用@JsonIgnore

    例如,您想从序列化中排除a(只想得到b、c、d

    使用@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
    
    }
    

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

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

    解决这个问题的惯用方法是创建DTO(数据传输对象)。Java不太喜欢“有时是这些值,有时不是”,因为它会导致API不一致并破坏强类型。@Christopher如果我总是只想返回a和b,这种情况会改变吗?在现有的DTO类中,用“@JsonInclude(JsonInclude.Include.NON_EMPTY)”注释该类然后在返回之前从foo将属性设置为null。您可以查看GraphQL,从中可以定义应该返回的内容。如果您永远不想返回给定的属性,请在其上使用
    @JsonIgnore
    。如果需要在不同位置返回不同的属性集,请使用
    DTO
    s。
    @JsonView(Views.Public.class)
    @RequestMapping("/items/{id}")
    public Item getItemPublic(@PathVariable int id) {
        return ItemManager.getById(id);
    }