【问题标题】:JSON parse error: Cannot deserialize instance of `java.lang.LongJSON解析错误:无法反序列化`java.lang.Long的实例
【发布时间】:2020-04-13 06:56:43
【问题描述】:

我正在使用 Spring boot 我尝试创建一个新学生。

@RequestMapping(path="/student/create", method=RequestMethod.POST)<br>
     public ResponseEntity<String> createStudent(@RequestBody Long nummer, String firstname, String lastname){<br>
      service.createStudent(matrikelnummer, vorname, nachname);<br>
      return new ResponseEntity<String>("gut gemacht", HttpStatus.OK);

这是我的RequestBody RESTCLIENT

{"nummer":15557,"firstname":"toti","lastname":"Innna"}

我有这个错误

{"timestamp":"2019-12-20T19:41:30.083+0000","status":400,"error":"Bad Request","message":"JSON 解析错误:无法反序列化 java.lang.Long 超出 START_OBJECT 令牌;嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:不能 从 START_OBJECT 令牌中反序列化 java.lang.Long 的实例\n 在 [来源:(PushbackInputStream);行:1,列: 1]","trace":"org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误:无法反序列化 java.lang.Long 的实例 START_OBJECT 令牌;嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:不能 从 START_OBJECT 令牌中反序列化 java.lang.Long 的实例\n 在 [来源:(PushbackInputStream);行:1,列:1]\r\n\tat

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

    在您的示例中,映射器希望主体呈现一个 Long 对象,但您将其传递给 Student 对象。这不匹配,因此会引发异常。

    不必将学生的所有字段作为单独的方法参数列出,您可以将 Student 对象作为 RequestBody 参数传递。 然后,对象映射器将尝试从提供的 JSON 解析 Student 实例。

    例子:

    @RequestMapping(path="/student/create", method=RequestMethod.POST)
    public ResponseEntity<String> createStudent(@RequestBody Student student){
        service.createStudent(student);
        return new ResponseEntity<String>("gut gemacht", HttpStatus.OK);
    }
    

    【讨论】:

    • @Poeterjan 首先谢谢你。但问题是,我在我的服务类中定义了方法。
    • 如果你想使用完整的 JSON 作为请求体,你需要 Student 对象作为 API 中的参数。如果您想使用不同的参数,请尝试使用 @RequestParameter 而不是 RequestBody(适用于所有参数)。
    • service.createStudent(student.getMatrikelnummer(), student.getVorname(), student.getNachname());
    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 2020-12-10
    • 2021-05-11
    • 2020-04-03
    • 2020-07-14
    • 1970-01-01
    • 2020-04-18
    • 2018-01-21
    相关资源
    最近更新 更多