RequestBody + JSON

时间:2016-08-29 11:01:18

标签: java json spring

我将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发送到控制器时,Controller会看到相同的url,但是无法将JSON反序列化为Java(我认为)。因为,当我尝试发送JSON - { title : "Title" }和控制器等待参数 - @RequestBody String note时,它可以轻松地显示它。

我正在尝试做什么,https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/中的内容并在servlet.xml中包含适配器,但效果相同。

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

3 个答案:

答案 0 :(得分:0)

确保在请求的标题中添加了内容类型为“application / json”。

答案 1 :(得分:0)

添加@RequestMapping(值=" / {username} / add",method = POST,生成=" application / json"

答案 2 :(得分:0)

如何发现问题: 将String发送到您的控制器并尝试创建您的对象。将断点放到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映射器逻辑之间存在一些冲突。