Spring启动:@Requestbody GET的自动JSON消息转换器不起作用

时间:2017-02-24 08:03:06

标签: java json spring rest spring-boot

自动邮件转换不适用于下一个Rest.GET。如何使用自动JSON消息转换?我在没有解决重要问题的情况下阅读了许多不同

据说Spring Boot有很多标准的消息转换器。

Q1:为什么邮件转换失败?

Q2:我真的应该将Jackson JSON转换器添加到消息转换器列表中吗?怎么样?

POJO对象是:

public class CacheCoordinateRange {
    private double latitudeMin;
    private double latitudeMax;
    private double longitudeMin;
    private double longitudeMax;

    public CacheCoordinateRange() { }
    public CacheCoordinateRange( double latMin, double latMax, double lonMin, double lonMax) {
        this.latitudeMin = latMin;
        this.latitudeMax = latMax;
        this.longitudeMin = lonMin;
        this.longitudeMax = lonMax;
    }
    ... getters and setters

Rest控制器包括:

@RequestMapping(method = RequestMethod.GET, value = "/coordinaterange", produces = { "application/json" }, consumes = MediaType.ALL_VALUE )
    public List<Items> findByCoordinateRange( @RequestBody CacheCoordinateRange coordinateRange) {
return cacheRepository.findByLatitudeBetweenAndLongitudeBetween(  coordinateRange.getLatitudeMin(),
                coordinateRange.getLatitudeMax(), coordinateRange.getLongitudeMin(), coordinateRange.getLongitudeMax());
    }

其余(测试)模板是:

CacheCoordinateRange range = new CacheCoordinateRange(  52.023456, 52.223456, -12.0234562, -12.223456);
HttpHeaders headersRange = new HttpHeaders();
headersRange.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entityRange = new HttpEntity( range,headersRange);
ResponseEntity<SolvedCache[]> resultRange = restTestTemplate.exchange(solvedCacheRestServices + "/coordinaterange", HttpMethod.GET, entityRange, SolvedCache[].class);
        objects = responseEntity.getBody();

错误是:

WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.util.List<nl.xyz.caches.Cache> nl.xyz.caches.SolvedCacheServices.findByCoordinateRange(nl.xyz.caches.CacheCoordinateRange)

1 个答案:

答案 0 :(得分:3)

问题不在于转换器未注册,而是找不到要转换的主体这一事实。

将您的控制器更改为POST并调用RestTemplate以使用该操作,它将起作用:

@RequestMapping(method = RequestMethod.POST, value = "/coordinaterange", produces = { "application/json" }, consumes = MediaType.ALL_VALUE )
public List<Items> findByCoordinateRange( @RequestBody CacheCoordinateRange coordinateRange) {
     return cacheRepository.findByLatitudeBetweenAndLongitudeBetween(  coordinateRange.getLatitudeMin(), coordinateRange.getLatitudeMax(), coordinateRange.getLongitudeMin(), coordinateRange.getLongitudeMax());
}
ResponseEntity<SolvedCache[]> resultRange = restTestTemplate.exchange(solvedCacheRestServices + "/coordinaterange", HttpMethod.POST, entityRange, SolvedCache[].class);
objects = responseEntity.getBody()

来自@RequestBody的文档:

  

注释指示方法参数应绑定到正文   的网络请求。请求的主体通过   HttpMessageConverter解析方法参数取决于   请求的内容类型。可选地,可以进行自动验证   通过使用@Valid注释参数来应用。支持   Servlet环境中带注释的处理程序方法。

GET请求不会发送正文。