java - 400 在 Spring MVC 4 Rest 中转换 JSON 时出错

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

我正在将 JSON 对象发送到 Java Rest 服务,并收到 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

最佳答案

更改此行:

data: bill,

对此:

data: JSON.stringify(bill),

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

关于java - 400 在 Spring MVC 4 Rest 中转换 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892452/

相关文章:

java - Gson处理多个json根元素

java - 无法理解克隆

json - Swift - 从 JSON 响应创建数据模型

java - 使用 gson 反序列化对象的特定 JSON 字段

java - 如何在java中使用Indexof()方法

java - 通过转储方法调用来模拟客户端 Activity 以记录和模拟 java 中的使用

json - 如何在 Kotlin 中使用 Gson 解析具有动态字段名称的 JSON?

rest - 在 Tomcat 上使用 RESTeasy

java - 一个 web.xml 中的两个 DispatherServlet

python - flask-restful 嵌套资源