发布到Spring Controller给出404 Bad Request

时间:2015-07-13 22:29:34

标签: java ajax spring spring-mvc jackson

我有这个ajax电话

$.ajax({
      headers: {
        'Content-Type': 'application/json'
      },
      url: urlString,
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({
         "field1": 1,
         "field2": "foo",
         "field3": "meh"
      })
      })
      .done(function (dataFromServer) {
         //blah
      })
      .fail(function (jqXHR) {
           console.log(jqXHR);
      });

调用此Spring Controller

@RequestMapping(value="more/updateThisTable", method=RequestMethod.POST)
public void updateThisTable(@RequestBody String jsonInput) throws JsonProcessingException, IOException {
    TableDTO t;
    TableImporter tImp = null;
    t= crewImp.getTableDTO(jsonInput);
    System.out.println(t);
    tableService.updateThisTable(t);
};

调用此导入程序

public TableDTO getTableDTO(String json) throws JsonProcessingException, IOException{
    TableDTO tDTO = new TableDTO();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(json);

    tDTO.setId(root.path("field1").asInt());
    tDTO.setCrewGroupId(root.path("field2").asText());
    tDTO.setName(root.path("field3").asText());

    return tDTO;
}

我在浏览器控制台中收到此错误消息

"Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token↵ at [Source: java.io.PushbackInputStream@124b300; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token↵ at [Source: java.io.PushbackInputStream@124b300; line: 1, column: 1]"

我正在使用Jackson尝试从JSON转到Java DTO。我收到了这个错误,并且不知道如何修复。

1 个答案:

答案 0 :(得分:1)

好的 - 让你的代码看起来像这样:

@RequestMapping(value="more/updateThisTable", method=RequestMethod.POST, headers="Accept=application/json")
public void updateThisTable(@RequestBody TableDTO t) throws JsonProcessingException, IOException {
    System.out.println(t);
    tableService.updateThisTable(t);
};

此外,F12您的浏览器并查看外发邮件以确保其合法的JSON。