【问题标题】:400 Error converting JSON in Spring MVC 4 Rest在 Spring MVC 4 Rest 中转换 JSON 时出现 400 错误
【发布时间】:2014-11-12 17:03:31
【问题描述】:

我正在向 Java Rest 服务发送一个 JSON 对象,并得到一个 400 Bad Request 错误作为回报。我正在通过 Angular JS 服务发送请求。

Java 配置:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "gov.mt.dphhs.bts.rest")
public class MvcConfig extends WebMvcConfigurerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(MvcConfig.class);

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        logger.debug("Initializing the Hibernate Aware Jackson Mapper for JSON.");
        super.configureMessageConverters(converters);
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
    }
}

Java REST 服务:

 public class AbstractRestController<T, I extends Serializable> {

    private final GenericService<T, I> service;

    public AbstractRestController(GenericService<T, I> service) {
        this.service = service;
    }

    /**
     * Handles request to save entity of type T
     * 
     * @param entity
     *            - the entity to be saved
     * @return the saved entity
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody T save(@RequestBody T entity) {
        return service.save(entity);
    }  

...

@RestController
@RequestMapping(value = "/rest/bill")
public class BillRestController extends AbstractRestController<Bill, Long>

角度服务:

(function(){
    var app = angular.module("billDetailsServiceModule", []);
    app.service('billDetailsService', function($log, $http){ 
          this.save = function(bill){ 
              return $http({
                  url: 'api/rest/bill/save', 
                  method: 'POST',
                  data: bill, 
                  headers: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'Accept': 'application/json;odata=verbose'
                    }
              });
          };
})();

从同一服务调用以获取 REST 服务中的方法可以正常工作。我已经用 Fiddler 捕获了请求,根据 JSONLint,JSON 对象格式正确。我正在使用 Jackson 2.4.3 和 Spring 4.1.0。我已经阅读了尽可能多的类似问题,但没有一个解决方案适合我。

编辑:此处粘贴的日志:http://chopapp.com/#hpc3axxc

【问题讨论】:

  • 将您的 Spring 日志转为 DEBUG 并向我们展示记录的内容。
  • 我不相信 Spring 足够聪明地告诉 T entity 应该是 Bill
  • 我尝试将方法从抽象类移动到子类,而行为没有改变。我添加了一个日志链接,但我找不到任何特别有趣的内容。
  • 将您的日志转为调试级别。只显示为一个请求周期写入的日志,否则我们将读取几天的日志。
  • 这正是我所做的。根本没有为请求写入日志。

标签: java json rest spring-mvc http-status-code-400


【解决方案1】:

改变这一行:

数据:账单,

到这里:

数据:JSON.stringify(bill),

为了捕获此类错误,我使用Burp HTTP Proxy 之类的工具来查看所有原始请求。

【讨论】:

  • 你如何解决我已经用 Fiddler 捕获了请求,根据 JSONLint,JSON 对象格式正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2017-04-28
相关资源
最近更新 更多