使用Jackson读取JSON时遭遇数组反序列化错误的求助
问题分析与解决方案
错误根源
你的JSON数据中,每个人员对象的items是数组类型(包含多个Item对象),但People实体类中对应的字段定义为private Item item;(单个Item对象),类型不匹配导致Jackson无法完成反序列化,抛出MismatchedInputException。
错误日志里的through reference chain: ... People["item"]也明确指向了这个字段的类型不匹配问题。
修复步骤
- 修改People类的字段定义
将单个Item对象改为List<Item>(或Item[]数组),字段名要和JSON中的items保持一致:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class People { private String name; private double height; private double weight; // 改为List<Item>,字段名与JSON的items对应 private List<Item> items; // 完整的getter和setter方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } // 可选:重写toString方法方便打印查看结果 @Override public String toString() { return "People{" + "name='" + name + '\'' + ", height=" + height + ", weight=" + weight + ", items=" + items + '}'; } }
- 确保Item类的getter/setter完整
你的Item类代码结构没问题,但要确保实现了完整的getter、setter方法,可选重写toString:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Item { private String name; private int number; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public String toString() { return "Item{" + "name='" + name + '\'' + ", number=" + number + '}'; } }
- 测试代码无需修改
原有的TestClient代码可以保持不变,Jackson会自动将JSON中的items数组反序列化为List<Item>对象。
验证结果
修改后运行测试代码,System.out.println(usrPost[2]);会打印出Robert的完整信息,包括他的两个Item对象,不会再抛出反序列化异常。
内容的提问来源于stack exchange,提问作者Neesh
相关产品推荐
相关产品推荐

