400 Error converting JSON in Spring MVC 4 Rest

1.1k views Asked by At

I'm sending a JSON object to a Java Rest service and getting a 400 Bad Request error in return. I am sending the request via an Angular JS service.

Java Configuration:

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

 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>

Angular Service:

(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'
                    }
              });
          };
})();

Calls from the same service to get methods in the REST service work just fine. I have captured the request with Fiddler, and according to JSONLint the JSON object is well formed. I'm using Jackson 2.4.3 and Spring 4.1.0. I've read as many similar questions as I can find, and none of the solutions work for me.

EDIT: Logs pasted here: http://chopapp.com/#hpc3axxc

1

There are 1 answers

1
Vetsin On

Change this line:

data: bill,

To this:

data: JSON.stringify(bill),

To catch errors like this I use tools like Burp HTTP Proxy to view all raw requests.