我正在为 Spring 的学习编写休息服务。我想从控制器返回动态响应(具有多个属性的 Json)。例如,我有一个方法,默认情况下我返回产品列表和 Spring,使用消息转换器将其转换为 Json。它工作正常。
@RequestMapping(value = { "" }, method = RequestMethod.GET)
public ResponseEntity<?> greet(@PathVariable Optional<Integer> productId) {
List<Products> products = productService.findAllCategories();
int count = products.size(); // also want to include this as count like below response
return new ResponseEntity<List<Products>>(products, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
现在我想要这样的回应 Json
{
"count": 23,
"products":[
{..},
{..}
]
}
Run Code Online (Sandbox Code Playgroud)
计数显示列表计数。我如何返回这样的响应。或者指导我了解返回具有多个属性的 Json 等场景的最佳实践。