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

How to return Json with Multiple properties by using ResponseEntity in Spring RestController

我正在为 Spring 中的学习编写休息服务。我想从控制器获得 return 动态响应(Json 具有多个属性)。例如,我有一个方法,其中我 returning 产品列表和 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

{
  "count": 23,
  "products":[
     {..},
     {..}
   ]
}

计数显示列表 count.How 我 return 这样的响应。或者指导我了解具有多个属性的 returning Json 等场景的最佳实践。

稍加改进即可实现您的目标。

为产品创建包装。像

class ProductsDTO {

  private int count;
  private List<Products> products;

  /* create setters and getters for the fields */ 

}

然后在您的 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);
}

编辑:

@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>

并且有一个 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);
}

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

测试一下..

  1. 命令行-

     curl -H "Accept: application/json" -H "Content-type: application/json" -X GET http://localhost:8080/api/locations
    
  2. 浏览器

http://localhost:8080/api/locations

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

我已经完成了这个,但我不知道这是不是一个好习惯。

@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;
    }
}

Output

@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);
}