如何使用Spring RestController中的ResponseEntity返回具有Multiple属性的Json

时间:2016-11-23 12:48:30

标签: 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);
}

现在我想要像这样回应Json

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

统计显示列表计数。如何返回这样的响应。或者引导我查看场景的最佳实践,例如返回具有多个属性的Json。

4 个答案:

答案 0 :(得分:3)

进一步改善可以实现您的目标。

为产品创建包装器。像

这样的东西
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. 浏览器

  3. http://localhost:8080/api/locations

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

答案 1 :(得分:3)

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

输出

enter image description here

答案 2 :(得分:1)

我已经完成了这项工作,但我不知道这是好的做法。

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

答案 3 :(得分:0)

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