You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jackson反序列化报Cannot deserialize instance of `model.UsersPajo`错误怎么解决

反序列化失败原因及修复方案

核心错误原因

  • 格式不匹配:你代码中使用Arrays.toString(usersPajos2)得到的information是Java对象自定义的toString()拼接字符串,不属于标准JSON格式,Jackson无法识别这种结构完成反序列化。
  • 类型不匹配:你的JSON文件根结构是数组,第一次读取得到的也是UsersPajo[]数组类型,后续反序列化时指定的目标是单个UsersPajo类,Jackson读取到数组开头标记后无法转换为单个对象,直接抛出MismatchedInputException异常。
  • 实体类缺失必要结构:UsersPajo以及关联的Address、Geo、Company类仅提供了getter方法,没有无参构造方法和属性对应的setter方法,Jackson反序列化时无法实例化对象并完成属性赋值,属于潜在错误点。

修复方案

  1. 先完善实体类结构:给所有相关实体类补充无参构造方法、所有属性对应的setter方法,若使用Lombok可直接给类添加@NoArgsConstructor、@Data注解简化代码。
  2. 移除多余的转换逻辑:你第一次从文件读取后已经得到了UsersPajo[]数组对象,直接操作该数组即可,不需要额外转字符串再反序列化,徒增性能消耗。
  3. 如果确实需要做Java对象转JSON字符串再反序列化的操作,使用Jackson提供的序列化方法,并且保证反序列化目标类型和结构匹配:
public static String readUserFile(String titleFile) {
    String pathJSONFile = "src/main/resources/" + titleFile + ".json";
    ObjectMapper objectMapper = new ObjectMapper();
    File jsonFile = new File(pathJSONFile);
    UsersPajo[] usersPajos2= null;
    UsersPajo usersPajo = null;

    try {
        // 第一步读取文件得到数组对象
        usersPajos2 = objectMapper.readValue(jsonFile, UsersPajo[].class);
        System.out.println("_usersPajos2___" + usersPajos2);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // 如果需要转JSON字符串,使用objectMapper的writeValueAsString方法
    String information = null;
    try {
        information = objectMapper.writeValueAsString(usersPajos2);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    // 反序列化时类型要匹配,如果要得到数组就用数组类型
    try {
        UsersPajo[] resultArray = objectMapper.readValue(information, UsersPajo[].class);
        // 如果需要单个对象,从数组中取出对应下标元素即可
        usersPajo = resultArray[0];
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    // 补充你的返回逻辑
    return information;
}

内容的提问来源于stack exchange,提问作者Денис Задорожний

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:24:07