将JSON转换为Java类有问题。
控制器@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;
}
}
所以,当我发送json到控制器,控制器看到相同的url,但不能反序列化json到Java(我认为)。因为,当我尝试发送JSON - { title : "Title" }
时,控制器等待参数- @RequestBody String note
,它可以很容易地显示它。
我试着做,什么是在https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/和servlet.xml中包含适配器,但效果相同。
$.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("");
}
})
添加@RequestMapping(value ="/{username}/Add ", method = POST, produces =" application/json")
请确保在请求的header中添加了content-type到"application/json"
如何捕捉问题:将字符串发送到控制器并尝试创建对象。给objectMapper.readValue()设置断点,并检查到底是什么问题;
@RequestMapping(value = "/{username}/add", method = POST)
public void add(@RequestBody String note) {
ObjectMapper objectMapper = new ObjectMapper();
NoteModel noteModel = objectMapper.readValue(result, NoteModel.class);
}
我认为默认的ObjectMapper和JSON映射器逻辑之间存在一些冲突。