简体   繁体   中英

Post to Spring Controller giving 404 Bad Request

I have this ajax call

$.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);
      });

calling this 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);
};

calls this importer

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;
}

I get this error message in my browser console

"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]"

I am using Jackson to try go from JSON to a Java DTO. I am getting this error and don't know how to fix.

Ok - have your code look like this:

@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);
};

Also, F12 your browser and view the outgoing message to make sure its legit JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM