Reputation: 109
I have problem with convert JSON to Java class.
Controller
@RequestMapping(value = "/{username}/add", method = POST)
public void add(@RequestBody NoteModel note) {
System.out.println(note.getTitle());
}
JSON
{
title : "Title",
text : "Text"
}
NoteModel
public class NoteModel {
private String title;
private String text;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
So, when I send json to the controller, Controller see same url, but can't deserialize JSON to Java (I think). Because, when I try, to send JSON - { title : "Title" }
, and controller wait argument - @RequestBody String note
, it can easily display it.
I'm try to do, what was in https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/ and include adapter in servlet.xml, but was the same effect.
AJAX
$.ajax({
type : "POST",
contentType : "application/json; charset=utf-8",
url : window.location.pathname,
data : JSON.stringify({
title : $("#titleId").val(),
text : $("#textId").val()
}),
success: function () {
$("#titleId").val("");
$("#textId").val("");
}
})
Upvotes: 0
Views: 3265
Reputation: 23
how to catch the problem: Send the String to your controller and try to create your object. Put breakpoint to objectMapper.readValue() and check what is the exactly problem;
@RequestMapping(value = "/{username}/add", method = POST)
public void add(@RequestBody String note) {
ObjectMapper objectMapper = new ObjectMapper();
NoteModel noteModel = objectMapper.readValue(result, NoteModel.class);
}
I think that there is some conflict between default ObjectMapper and JSON mapper logic.
Upvotes: 0
Reputation: 6531
Add @RequestMapping(value = "/{username}/add", method = POST, produces = "application/json")
Upvotes: 1
Reputation: 469
Make sure that you have added content-type to "application/json" in header of your request.
Upvotes: 0