How to return Json with Multiple properties by using ResponseEntity in Spring RestController
我正在编写Springrest学习服务。我想从控制器返回动态响应(具有多个属性的Json)。例如,我有一个方法,默认情况下,我使用消息转换器将产品列表和Spring返回,将其转换为Json。运行正常。
1 2 3 4 5 6 7 | @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); } |
现在我要像这样回复杰森
1 2 3 4 5 6 7 | { "count": 23, "products":[ {..}, {..} ] } |
显示列表计数。我如何返回这样的响应。或指导我获得场景的最佳实践,例如返回具有多个属性的Json。
仅需一点点改进就可以实现您想要的。
为产品创建package。
之类的东西
1 2 3 4 5 6 7 8 | class ProductsDTO { private int count; private List<Products> products; /* create setters and getters for the fields */ } |
,然后在您的REST调用中
1 2 3 4 5 6 7 8 9 10 | @RequestMapping(value = {"" }, method = RequestMethod.GET) public ResponseEntity< ? > greet(@PathVariable Optional<Integer> productId) { List<Products> products = productService.findAllCategories(); int count = products.size(); ProductsDTO productsDTO = new ProductsDTO(); productsDTO.setCount(count); productsDTO.setProducts(products); return new ResponseEntity<ProductsDTO>(productsDTO, HttpStatus.OK); } |
编辑:
@Shams Tabraiz Alam
-不确定您要形成的结果类型是否正确,因为当您说计数和列出时,您返回的是实体(产品)列表和计数结果(产品计数,产品列表]。不确定添加其他数据的目的,因为它删除了返回列表的实际含义并将其计为结果。无论如何,这就是我的意思。
根据您的情况,如果您不想使用DTO并使用地图添加所需的任意多个属性,我已经制作了一个示例代码(行家方式)
添加Spring和其他现有依赖项,然后将Jackson依赖项添加到pom.xml
1 2 3 4 5 6 7 8 9 10 | <dependency> <groupId>com.fasterxml.jackson.core</groupId> jackson-core</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> jackson-databind</artifactId> <version>2.8.5</version> </dependency> |
并有一个REST控制器
1 2 3 4 5 6 7 8 9 10 11 12 | @RequestMapping(value ="/locations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity< ? > getAll() { List<Location> locations = locationService.getLocations(); List<Country> countries = countryService.getCountries(); Map<String, Object> result = new HashMap<String,Object>(); result.put("count",locations.size()); result.put("locations",locations); result.put("countries",countries); // Add any additional props that you want to add return new ResponseEntity<Map<String,Object>>(result, HttpStatus.OK); } |
在本地Web服务器(端口8080)中构建和部署代码,或者使用maven在命令行中运行-mvn tomcat7:run
测试..
命令行-
1 | curl -H"Accept: application/json" -H"Content-type: application/json" -X GET http://localhost:8080/api/locations |
浏览器
http:// localhost:8080 / api / locations
完整的代码在这里-https://github.com/satya-j/loco
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | @RestController @RequestMapping("/api") public class RestApiController { @Autowired RepoCity repoCity; @Autowired RepoCountry repoCountry; @Autowired RepoLanguage repoLanguage; @GetMapping("/allTotal") public Map actionAllTotal() { Map map = new HashMap(); map.put("repoCity",repoCity.count()); map.put("repoCountry",repoCountry.count()); map.put("repoLanguage",repoLanguage.count()); Map result = new HashMap();; result.put("result",map); return result; } @GetMapping("/country-detail/{id}") public Map actionCountryDetail(@PathVariable("id") String id) { Map result = new HashMap(); result.put("result",repoCountry.findOne(id)); return result; } } |
Output
我已经完成了此操作,但是我不知道这是否是一个好习惯。
1 2 3 4 5 6 7 8 9 10 11 | @RequestMapping(value = {"/{productId}","" }, method = RequestMethod.GET) public ResponseEntity< ? > greet(@PathVariable Optional<Integer> productId) { List<Products> products = productService.findAllCategories(); HashMap<String, Object> hmap = new HashMap<String, Object>(); hmap.put("count", products.size()); hmap.put("products", products); // Now I can put as many properties as I want return new ResponseEntity<HashMap<String, Object>>(hmap, HttpStatus.OK); } |
1 2 3 4 5 6 7 8 9 | @RequestMapping(value ="/{pid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Map<String, Object>> greet(@PathVariable(value ="pid", required = false) Integer productId) { Map<String, Object> result = new HashMap<String,Object>(); result.put("count",locations.size()); result.put("locations",locations); result.put("countries",countries); return ResponseEntity.ok(result); } |