【问题标题】:How to correctly send a json to a RestController using ajax?如何使用 ajax 正确地将 json 发送到 RestController?
【发布时间】:2016-08-09 14:23:39
【问题描述】:

我正在尝试将 json 发送到 api,但出现此错误:

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'status': was expecting ('true', 'false' or 'null')

这是javascript:

$("body").on('click','.btn-danger' ,(function (){
    var id = $(this).val();
    var data = {"status": "canceled",
                "response": ""};
    console.log(data);
    $.ajax ({
        type: 'PUT',
        url: '/api/pendingrequests/' + id,
        contentType: "application/json",
        data: data,
        dataType : "html"
    }).done (function () {
        $(this).hide();
    });
}));

控制器:

@RequestMapping(value = "/api/pendingrequests/{requestId}", method = RequestMethod.PUT)
    public ResponseEntity updateRequestStatus(@PathVariable Long requestId, @RequestBody HolidayRequestAction action) throws IOException {
        return updateRequestStatusService.updateRequest(requestId, action);
    }

以及我试图从请求中接收的 POJO:

public class HolidayRequestAction {
    private String status;
    private String response;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

为什么我会得到这个解析异常?可能是什么问题?

【问题讨论】:

  • 您是否尝试过传递 JSON 字符串而不是对象? var data = '{"status":"canceled","response":""}';
  • 这个错误不是已经描述得很清楚了吗?令牌“状态”:期待(“真”、“假”或“空”),表示数据中的状态属性应为真/假/空

标签: javascript json ajax rest


【解决方案1】:

您的问题包含答案:'status': was expecting ('true', 'false' or 'null')

所以你不能发送其他值然后'true', 'false' or 'null'

但是在请求中去"status": "canceled"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2020-02-22
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多