本文介绍了如何让 HATEOAS 渲染空的嵌入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常 CollectionModel
会返回一个 _embedded
数组,但在这个例子中:
Usually CollectionModel
will return an _embedded
array, but in this example:
@GetMapping("/{id}/productMaterials")
public ResponseEntity<?> getProductMaterials(@PathVariable Integer id) {
Optional<Material> optionalMaterial = materialRepository.findById(id);
if (optionalMaterial.isPresent()) {
List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
CollectionModel<ProductMaterialModel> productMaterialModels =
new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
toCollectionModel(productMaterials);
return ResponseEntity.ok().body(productMaterialModels);
}
return ResponseEntity.badRequest().body("no such material");
}
如果 productMaterials
为空 CollectionModel
将不会渲染 _embedded
数组,这会破坏客户端.有什么办法可以解决这个问题吗?
if the productMaterials
is empty CollectionModel
will not render the _embedded
array which will break the client. Is there any ways to fix this?
推荐答案
if (optionalMaterial.isPresent()) {
List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
CollectionModel<ProductMaterialModel> productMaterialModels =
new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
toCollectionModel(productMaterials);
if(productMaterialModels.isEmpty()) {
EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(ProductMaterialModel.class);
Resources<Object> resources = new Resources<>(Arrays.asList(wrapper));
return ResponseEntity.ok(new Resources<>(resources));
} else {
return ResponseEntity.ok().body(productMaterialModels);
}
}
这篇关于如何让 HATEOAS 渲染空的嵌入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!