当前位置: 首页 > 知识库问答 >
问题:

Jackson无法读取文档:无法识别的标记“联系表单”:需要('true'、'false'或'null')

南宫鸿晖
2023-03-14
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]
$('#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

}

和ContactForm

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,这个主体与JSON.stringify(contactForm)相同,一切都很顺利,所以Jackson在幕后做了一些奇怪的事情...

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

共有1个答案

荣晨朗
2023-03-14

在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试图将查询参数解释为请求主体,但失败了。

 类似资料: