Spring Hateoas JSON API列表返回无属性问题求助
解决Spring Hateoas JSON API返回实体列表的问题
问题原因
直接返回List<EntityModel<Movie>>无法被Spring Hateoas JSON API的消息转换器正确处理——JSON API规范要求列表响应的data字段为数组结构,而Spring Hateoas需要用CollectionModel作为容器包装实体列表,才能触发符合规范的序列化逻辑。
解决方案
修改接口返回类型为CollectionModel<EntityModel<Movie>>,通过CollectionModel.of()方法包装实体列表:
修改后的控制器代码
import static com.toedter.spring.hateoas.jsonapi.MediaTypes.JSON_API_VALUE; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.CollectionModel; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value ="/cont", produces = JSON_API_VALUE) public class MovieController { // 单个实体接口(保持原有逻辑) @RequestMapping("/getMovie") public ResponseEntity<EntityModel<Movie>> getMovie(){ EntityModel<Movie> model = EntityModel.of(new Movie("1", "Star Wars")); return ResponseEntity.ok(model); } // 修改后的列表接口 @RequestMapping("/getMovieList") public ResponseEntity<CollectionModel<EntityModel<Movie>>> getMovieList(){ EntityModel<Movie> model1 = EntityModel.of(new Movie("1", "first movie")); EntityModel<Movie> model2 = EntityModel.of(new Movie("2", "second movie")); List<EntityModel<Movie>> list = new ArrayList<>(); list.add(model1); list.add(model2); // 用CollectionModel包装列表,触发JSON API规范序列化 CollectionModel<EntityModel<Movie>> collectionModel = CollectionModel.of(list); return ResponseEntity.ok(collectionModel); } }
预期响应格式
修改后将得到符合JSON API规范的列表响应:
{ "data": [ { "id": "1", "type": "movies", "attributes": { "title": "first movie" } }, { "id": "2", "type": "movies", "attributes": { "title": "second movie" } } ] }
额外注意事项
- 依赖版本兼容性:当前使用的
com.toedter:spring-hateoas-jsonapi:2.1.3需搭配Spring Boot 2.7.x或Spring Hateoas 1.4.x以上版本,你现有依赖中的spring-boot-starter-hateoas会自动匹配兼容版本。 - 若需分页支持,可改用
PagedModel替代CollectionModel,结合Spring Data的分页查询逻辑即可生成带分页元数据的JSON API响应。
内容的提问来源于stack exchange,提问作者Thejas
相关产品推荐
相关产品推荐

