Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何在构造JSON响应时删除空属性_Spring_Spring Boot - Fatal编程技术网

Spring 如何在构造JSON响应时删除空属性

Spring 如何在构造JSON响应时删除空属性,spring,spring-boot,Spring,Spring Boot,因此,我在SpringBoot中构建了一个简单的API,用于检索特定的书籍,并将其作者组成一个数据库。这本书有一个id,名字,出版年份和作者的外键。模型如下: @Entity @Table(name="book", schema = "book_store") public class Book { @Id private long id; private String name; private int released; @ManyToOne

因此,我在SpringBoot中构建了一个简单的API,用于检索特定的书籍,并将其作者组成一个数据库。这本书有一个id,名字,出版年份和作者的外键。模型如下:

@Entity
@Table(name="book", schema = "book_store")
public class Book {

    @Id
    private long id;
    private String name;
    private int released;
    @ManyToOne
    @JoinColumn(name="author_id")
    private Author author;

    public Book() {
    }

    public Book(String name, int released, Author author){
        this.name=name;
        this.released=released;
        this.author=author;
    }

    //And also the getters and setters
以下是存储库:

public interface BookRepository extends JpaRepository<Book, Long> {

}
作者被设置为null,这是我想要的,但是有没有办法使响应不返回
“author”:null

因为在这种情况下,“author”字段几乎是无用的,我想完全删除它,因为我想有一个更干净的响应

我还试图通过构建一个包含键和值的映射列表来创建自定义JSON响应。虽然该方法确实有效,但它不会返回图书列表,这是我希望控制器最终返回的


有人知道其他方法吗?

您可以简单地添加@JsonInclude注释,然后包含非空值

@JsonInclude(JsonInclude.Include.NON_NULL)
@ManyToOne
@JoinColumn(name="author_id")
private Author author; 

在这种情况下,我通常做的是,正如您所说,在控制器中返回一个自定义实体列表,这些实体将是没有作者的书籍。这是最简单的方法,控制器层负责解析答案

为了好玩,我将添加一个疯狂的想法:

存储库中

@Query("select id,name,released from Book") // you get all except the author
List<Book> findBooksWithoutAuthor();
@Query(“选择id,name,从书中发布”)//您将获得除作者之外的所有内容
列出FindBookswithout author();
@JsonInclude(JsonInclude.Include.NON_NULL)
@ManyToOne
@JoinColumn(name="author_id")
private Author author; 
@Query("select id,name,released from Book") // you get all except the author
List<Book> findBooksWithoutAuthor();