猿问

JSON 没有显示它在 Postman 中应该如何显示

当我尝试调用 REST 端点时,我的 Postman 有一些奇怪的行为。有一个永无止境的循环。我在 stackoverflow 上找到了一个解决方案,@JsonIgnore 注释将删除这个奇怪的循环(我在下面的 Book 实体中有它)但是当我尝试在 Postman 中列出所有书籍时,我看不到这些书籍的作者。是否有更好的解决方案来显示作者的书籍(删除 @JsonIgnore 注释)但也删除那个奇怪的循环?


Book.java


@Entity

public class Book {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String title;

    private String isbn;


    @ManyToMany

    @JsonIgnore // removed wierd loop with data

    @JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"),

            inverseJoinColumns = @JoinColumn(name = "author_id"))

    private Set<Author> authors = new HashSet<>();


    public Book() {

    }

Author.java


@Entity

public class Author {


    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;

    private String forename;

    private String surname;


    @ManyToMany(mappedBy = "authors")

    private Set<Book> books = new HashSet<>();


    public Author() {

    }

BookController.java


@RestController

public class BookController {

    private BookService bookService;


    @Autowired

    public BookController(BookService bookService) {

        this.bookService = bookService;

    }


    // expose /books and get list of all books - GET

    @GetMapping("/api/books")

    public List<Book> getAllBooks() {

        return bookService.getAllBooks();

    }

AuthorController 与 BookController 相同。

这是 Book JSON 在 Postman 中的样子(这些书没有作者):

Postman 中的 Authors 没问题:

http://img3.mukewang.com/6437a1ba00018d2214780544.jpg

这是我从 Book 实体中删除 @JsonIgnore 时的循环:

http://img4.mukewang.com/6437a1cc0001103f14620446.jpg


鸿蒙传说
浏览 158回答 1
1回答

陪伴而非守候

使用@JsonIgnoreProperties注解为了忽略一个字段上的子字段,那么这个注解会忽略二级字段。Book&nbsp;&nbsp; &nbsp; - >&nbsp; authors&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -> books&nbsp; // this field is ignoredAuthor&nbsp;&nbsp; &nbsp; - >&nbsp; books&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -> authors // this field is ignored@ManyToMany@JsonIgnoreProperties("books")@JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"),&nbsp; &nbsp; &nbsp; &nbsp; inverseJoinColumns = @JoinColumn(name = "author_id"))private Set<Author> authors = new HashSet<>();@ManyToMany(mappedBy = "authors")@JsonIgnoreProperties("authors")private Set<Book> books = new HashSet<>();
随时随地看视频慕课网APP

相关分类

Java
我要回答