如何通过在 Spring RestController 中使用 ResponseEntity 返回具有多个属性的 Json

Sha*_*lam 1 spring spring-restcontroller

我正在为 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 等场景的最佳实践。

sat*_*a-j 5

再多一点改进就可以实现您的目标。

为产品创建包装器。就像是

class ProductsDTO {

  private int count;
  private List<Products> products;

  /* create setters and getters for the fields */ 

}
Run Code Online (Sandbox Code Playgroud)

然后在你的 REST 调用中

@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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

@Shams Tabraiz Alam - 不确定您想要形成的结果类型是否正确,因为当您说计数和列表时,您返回的实体(产品)列表及其计数结果完全有道理[产品数量,产品清单]。不确定添加额外数据的确切目的,因为它删除了返回列表的实际含义,并将其计为结果。无论如何,这就是我的观点。

对于您的情况,如果您不想使用 DTO 并使用地图添加任意数量的属性,我已经制作了一个示例代码(maven 方式)

添加 Spring 和其他现有的依赖项,然后将 Jackson 依赖项添加到pom.xml

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.5</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.5</version>
  </dependency>
Run Code Online (Sandbox Code Playgroud)

并有一个 REST 控制器,

@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);
}
Run Code Online (Sandbox Code Playgroud)

在本地 Web 服务器(端口 8080)中构建和部署代码或使用 maven 通过命令行运行 - mvn tomcat7:run

测试一下。。

  1. 命令行 -

     curl -H "Accept: application/json" -H "Content-type: application/json" -X GET http://localhost:8080/api/locations
    
    Run Code Online (Sandbox Code Playgroud)
  2. 浏览器

http://localhost:8080/api/locations

完整代码在这里 - https://github.com/satya-j/loco