如何在SpringRestController中使用ResponseEntity返回具有多个属性的Json

如何在SpringRestController中使用ResponseEntity返回具有多个属性的Json,spring,spring-restcontroller,Spring,Spring Restcontroller,我正在为春天的学习写休息服务。我想从控制器返回动态响应(具有多个属性的Json)。例如,我有一个返回产品列表的方法,默认情况下,Spring使用消息转换器将其转换为Json。工作很好 @RequestMapping(value = { "" }, method = RequestMethod.GET) public ResponseEntity<?> greet(@PathVariable Optional<Integer> productId) { List&

我正在为春天的学习写休息服务。我想从控制器返回动态响应(具有多个属性的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);
}

计数显示列表计数。我如何像这样返回响应。或者让我了解一些场景的最佳实践,例如返回具有多个属性的Json。

再多一些改进就可以实现您所期望的

为产品创建包装。差不多

class ProductsDTO {

  private int count;
  private List<Products> products;

  /* create setters and getters for the fields */ 

}
  • 浏览者


  • 完整的代码在这里-

    再多一点改进就可以实现您所期望的

    为产品创建包装。差不多

    class ProductsDTO {
    
      private int count;
      private List<Products> products;
    
      /* create setters and getters for the fields */ 
    
    }
    
  • 浏览者


  • 完整的代码在这里-

    我已经完成了,但我不知道这是否是一个好的实践

    @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);
    }
    
    @RequestMapping(值={”/{productId},“”},method=RequestMethod.GET)
    公共响应性问候(@PathVariable可选productId){
    列出产品=productService.findAllCategories();
    HashMap hmap=新的HashMap();
    hmap.put(“count”,products.size());
    hmap.put(“产品”,产品);
    //现在我可以放置任意数量的属性
    返回新的响应状态(hmap,HttpStatus.OK);
    }
    
    我已经完成了这项工作,但我不知道这是否是一种好的做法

    @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);
    }
    
    @RequestMapping(值={”/{productId},“”},method=RequestMethod.GET)
    公共响应性问候(@PathVariable可选productId){
    列出产品=productService.findAllCategories();
    HashMap hmap=新的HashMap();
    hmap.put(“count”,products.size());
    hmap.put(“产品”,产品);
    //现在我可以放置任意数量的属性
    返回新的响应状态(hmap,HttpStatus.OK);
    }
    
    输出

    输出

    @RequestMapping(value=“/{pid}”,method=RequestMethod.GET,products=MediaType.APPLICATION\u JSON\u value)
    public ResponseEntity greet(@PathVariable(value=“pid”,required=false)整数productId){
    映射结果=新的HashMap();
    result.put(“count”,locations.size());
    结果。放置(“位置”,位置);
    结果。put(“国家”,国家);
    返回ResponseEntity.ok(结果);
    }
    
    @RequestMapping(value=“/{pid}”,method=RequestMethod.GET,products=MediaType.APPLICATION\u JSON\u value)
    public ResponseEntity greet(@PathVariable(value=“pid”,required=false)整数productId){
    映射结果=新的HashMap();
    result.put(“count”,locations.size());
    结果。放置(“位置”,位置);
    结果。put(“国家”,国家);
    返回ResponseEntity.ok(结果);
    }
    

    假设我有另一个型号的客户,并且我想要同样的东西,那么我必须为其他型号的客户创建另一个类CustomersDTO,依此类推。我需要一个通用的解决方案。@ShamsTabraizAlam您在问题中具体返回{count:23,products:[]}。我回答了这方面的问题。如果您希望使用上述通用解决方案,就像希望返回结果(计数,对象列表),则需要在代码中对其进行建模。如果您需要通用解决方案,请创建一个接口X。让您要发送到响应的所有类扩展此X。使用属性修改响应类:计数和列表。所以你可以给你的响应类赋值计数和任何类型的X。@satya-j我刚才举了一个例子来演示。我需要这样的回答;答复。添加(“产品”,产品);回答。添加(“某物”,某物);在返回响应的末尾。@ShamsTabraizAlam您希望在计数中也包含“某物”的计数吗?假设我有另一个模型客户,并且我想要相同的东西,那么我必须使用CustomersDTO创建另一个类,以此类推,其他模型也是如此。我需要一个通用的解决方案。@ShamsTabraizAlam您在问题中具体返回{count:23,products:[]}。我回答了这方面的问题。如果您希望使用上述通用解决方案,就像希望返回结果(计数,对象列表),则需要在代码中对其进行建模。如果您需要通用解决方案,请创建一个接口X。让您要发送到响应的所有类扩展此X。使用属性修改响应类:计数和列表。所以你可以给你的响应类赋值计数和任何类型的X。@satya-j我刚才举了一个例子来演示。我需要这样的回答;答复。添加(“产品”,产品);回答。添加(“某物”,某物);在最后的回复中。@ShamsTabraizAlam你想数一数那个“东西”也包括在count中?创建它的包装器,将count和products属性设置到另一个bean中,并用新的bean productsTo替换列表,就像下面@satya-j所做的那样。@TechnoCrat假设我有另一个模型客户,我想要同样的东西,然后我还必须为其他模型制作另一个包装器,依此类推。我需要一个通用的解决方案,这样在运行时我可以返回任何格式的Json。在这种情况下,您只需要将新属性添加到ProductsTo类中,并在ProductsTo类下面添加列表,就像ProductsTo{private int count;private List products;private List customers;}基本上我想这样做。响应。添加(“计数”,计数);答复。添加(“产品”,产品);回答。添加(“某物”,某物);您可以使用@Valath提供的解决方案,或者按照我的建议添加新属性。我想这是不可能的,而且看起来也不太好。创建它的包装器,将count和products属性设置到另一个bean中,并用新的bean ProductsTo替换列表,就像下面@satya-j所做的那样。@TechnoCrat让我们假设我有另一个模型客户,我想要同样的东西,然后我必须制作另一个包装器,以此类推其他型号也有。我需要一个通用的解决方案,以便在运行时返回
    @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);
    }
    
     curl -H "Accept: application/json" -H "Content-type: application/json" -X GET http://localhost:8080/api/locations
    
    @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);
    }
    
    @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;
        }
    }
    
    @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);
    }