【问题标题】:Jackson Could not read document: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')杰克逊无法读取文档:无法识别的令牌“contactForm”:期待(“真”、“假”或“空”)
【发布时间】:2017-12-14 17:06:25
【问题描述】:

我想用 JQuery 向 Spring 控制器发送一个 POST 请求,但我不断从 jquery 收到此错误

Could not read document: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]

这是 POST 请求

$('#contactForm').on('submit', function(e){
        e.preventDefault();
        var contactForm = new Object;
        var firstName = $('#firstName').val();
        var lastName = $('#lastName').val();
        var email = $('#email').val();
        var message = $('#message').val();
        contactForm.firstName = firstName;
        contactForm.lastName = lastName;
        contactForm.email = email;
        contactForm.message = message;
        contactForm.accepted = true;
        console.log(JSON.stringify(contactForm));
        $.ajax({
            type: 'POST',
            url: '/checkContact.json',
            contentType : 'application/json; charset=utf-8',
            dataType: 'json',
            data: {
                contactForm: JSON.stringify(contactForm)

            },
            success: function(response){
                console.log(response)
                $('#success').text(response.message);
            },
            error: function(data){
                console.log(data.responseJSON.message);
            }
        })
    })

这是控制器

 @PostMapping("/checkContact.json")
       public @ResponseBody String sendContactForm(@Valid @RequestBody ContactForm contactForm, BindingResult result, HttpServletRequest request) throws MalformedURLException, JsonProcessingException{

//logic here

}

和联系表格

public class ContactForm {

    @NotNull
    @NotEmpty
    @ValidEmail
    private String email;

    @NotNull
    @NotEmpty
    private String firstName;

    @NotNull
    @NotEmpty
    private String lastName;

    @NotNull
    @NotEmpty
    private String message;

//  @AssertTrue
    private boolean accepted;

//getters and setters
}

我不知道到底发生了什么,因为例如,如果我尝试向控制器发送一个带有 POSTMAN 的 JSON 和这个 body,这与 JSON.stringify(contactForm) 相同,一切顺利,所以杰克逊在幕后做了一些奇怪的事情......

{
    "fistName": "John",
    "lastName": "Smith",
    "email": "a@a.aa",
    "message": "Hello"
    "accepted":true
}

【问题讨论】:

    标签: jquery json spring


    【解决方案1】:

    在你的 jQuery ajax 调用中调整你的数据值:

        $.ajax({
            type: 'POST',
            url: '/checkContact.json',
            contentType : 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(contactForm),
            success: function(response){
                console.log(response)
                $('#success').text(response.message);
            },
            error: function(data){
                console.log(data.responseJSON.message);
            }
        })
    

    正在发生的事情是 jQuery 正在将您的对象转换为查询参数字符串并发送它。这看起来像:

    contactForm=%7B%22fistName%22%3A%22John%22%2C%...
    

    Jackson 试图将查询参数解释为您失败的请求正文。

    这可以通过查看浏览器中的网络选项卡并查看请求正文来确认

    【讨论】:

    • 该死的!谢谢你的回答,现在很清楚了
    【解决方案2】:

    如果您在控制器中手动设置 ObjectMapper 类,如下所示。

        ObjectMapper obj = new ObjectMapper();
        obj.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        obj.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    

    或者

    1. 在提供的范围内向 javax.validation:validation-api 添加依赖项。
    2. javax.validation.constraints.NotNull 注释添加到您的字段。

    希望这会有所帮助。

    既然你已经添加了 SPRING 有一个标签,我会考虑从后端的角度来设置它。

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2012-01-14
      • 2021-12-31
      • 2015-09-28
      相关资源
      最近更新 更多