Recursive JSON view of an entity with one-to-many relationship in REST controller

前端 未结 3 799
失恋的感觉
失恋的感觉 2020-12-31 19:25

I\'m using SpringBoot and JPA to build a REST interface.

Now, I have a strange JSON returned for the list of products fetched from the database. Let\'s say that I h

3条回答
  •  难免孤独
    2020-12-31 19:42

    You're not doing anything wrong (at least at the code level it's rather conceptual) - json serializer just goes like this:

    1. Product - serialize it, but wait - there is a category field, so serializer must serialize the category field
    2. Category - serialize it, but wait - there is a products field, so serializer must serialize each of the product in the list
    3. Product - because your collection contains the product & product contains category it goes in a endless loop untill a timeout.

    You must use a view or just skip it.

    1. Use @JsonView

    2. Use a view as a POJO Return new ProductView that has all fields of product and a reference (category) to new CategoryView (you can end at this point) that has collection of (products) new ProductViewWithoutReferences, and so on

    3. Use @JsonIgnore on a collection of products

    And as a side note - if it's a @RestController and you're invoking "all-products" then it's a bit unusual to return something else than a list. Wrapping the response in a map is redundant. Many rest clients expect a list when they invoke list() method.

提交回复
热议问题