【问题标题】:Facing JSON parse issue, Cannot deserialize value of type `java.lang.String` from Array value jackson.databind.exc.MismatchedInputException面对 JSON 解析问题,无法从数组值 jackson.databind.exc.MismatchedInputException 反序列化类型为“java.lang.String”的值
【发布时间】:2022-09-24 18:57:47
【问题描述】:

尝试在我的邮递员请求中包含数组时遇到 JSON 解析问题:

{
    \"id\" : \"0\",
    \"number\":[\"2222\", \"3333\"]
}

宝约:

public class User {
    @Getter @Setter private String      id;
    @Getter @Setter  private String[]   number;

    //i\'ve also tried these:
    @Getter @Setter  private List<String>   number;
    @Getter @Setter  private ArrayList<String>  number;
}

控制器:

@PostMapping(\"/user\")
    public ResponseEntity<Object> getUser(@RequestBody(required=true)User user) {

痕迹:

  \"trace\": \"org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Cannot deserialize value of type `java.lang.String` from Array value (token `JsonToken.START_ARRAY`); 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize value of type `java.lang.String` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 13] 

    标签: java jackson jackson-databind


    【解决方案1】:

    我遇到过同样的问题。事实证明,当我从一个测试 JS 脚本发送消息时,Stomp.js 并没有自动序列化作为消息体传递的对象到 JSON,它所做的只是将它转换为一个字符串并将"[Object object]" 作为有效负载发送,因为前面有[,Jackson 将其解释为一个数组,并立即失败,因为它没想到会收到一个数组。

    client.publish({
      destination: '/app/publish',
      body: {
        id: 0,
        content: 'I am very frustrated',
        sender: 'test_user',
        chat: 0
      }
    }); // => "[Object object]"
    

    在将对象作为有效负载传递之前手动显式序列化对象做了以下事情:

    client.publish({
      destination: '/app/publish',
      body: JSON.stringify({
        id: 0,
        content: 'I am very frustrated',
        sender: 'test_user',
        chat: 0
      })
    }); // => {id: 0, ...}
    

    问题一直是Javascript。

    【讨论】:

      【解决方案2】:

      向您的类添加一个无参数构造函数并使其成为Serializable

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 2020-07-26
        • 2017-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多