Jackson解析嵌套JSON对象时LinkedHashMap转ObjectCategory异常的解决方法
解决Jackson解析时LinkedHashMap转自定义类的异常问题
这个问题我之前也碰到过!核心原因是Jackson在处理Map<String, Object>里的数组时,默认会把每个JSON对象转成LinkedHashMap,而不是你自定义的ObjectCategory类型,直接强制类型转换肯定会报错。下面给你两种靠谱的解决办法:
方法一:手动用ObjectMapper转换类型(适合不想新增太多类的场景)
你可以在unpackNested方法里,用Jackson的ObjectMapper把拿到的Map列表转换成List<ObjectCategory>,而不是直接强转。代码示例如下:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; // 确保你有ObjectMapper实例(可以全局初始化,或者依赖注入) private final ObjectMapper objectMapper = new ObjectMapper(); @JsonProperty("data") private void unpackNested(Map<String, Object> data) { // 先把detection取出为Map列表 List<Map<String, Object>> detectionItems = (List<Map<String, Object>>) data.get("detection"); // 用TypeReference告诉Jackson要转成的目标类型 this.categories = objectMapper.convertValue(detectionItems, new TypeReference<List<ObjectCategory>>() {}); }
方法二:定义完整的映射类(更规范,推荐)
其实不用手动拆嵌套,直接定义对应JSON结构的类,Jackson会自动帮你完成类型转换,代码更简洁易维护。
首先定义Data类来映射外层的data字段:
public class Data { @JsonProperty("detection") private List<ObjectCategory> detection; // getter和setter public List<ObjectCategory> getDetection() { return detection; } public void setDetection(List<ObjectCategory> detection) { this.detection = detection; } }
然后在你的主类里直接用Data类型接收:
@JsonProperty("data") private Data data; // 如果你需要保持原有的getCategories方法,可以这样封装 public List<ObjectCategory> getCategories() { return data != null ? data.getDetection() : Collections.emptyList(); }
另外要确保你的ObjectCategory类(包括内部的Coordinates类)的注解和字段完全匹配JSON结构:
public class ObjectCategory { @JsonProperty("category") private String category; @JsonProperty("coordinates") private Coordinates coordinates; @JsonProperty("accuracy") private String accuracy; // getters and setters // 嵌套的Coordinates类 public static class Coordinates { @JsonProperty("xmin") private String xmin; @JsonProperty("ymin") private String ymin; @JsonProperty("ymax") private String ymax; @JsonProperty("xmax") private String xmax; // getters and setters } }
这样修改后,再调用getCategories().get(0).getAccuracy()就不会再出现类型转换异常啦!
内容的提问来源于stack exchange,提问作者Mark Waugh
相关产品推荐
相关产品推荐

