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

Spring Boot中使用Jackson将嵌套JSON的Results列表转换为Recipe对象数组

问题解决方法

你遇到的报错是因为JSON顶层结构为对象,而你直接尝试将其反序列化为Recipe数组,类型不匹配导致触发MismatchedInputException,可以通过以下两种方式解决:

方案1:通过JsonNode中转提取目标字段(适合临时调用场景)

先将完整JSON解析为JsonNode节点,提取出Results字段后再反序列化为Recipe数组,代码示例如下:

ObjectMapper mapper = new ObjectMapper();
// 读取完整JSON为根节点
JsonNode rootNode = mapper.readTree(json);
// 提取Results字段节点,转换为Recipe数组
Recipe[] recipes = mapper.treeToValue(rootNode.get("Results"), Recipe[].class);

注意get()方法内的字段名需要和JSON顶层的key大小写完全匹配,若JSON里是小写results则修改为rootNode.get("results")。

方案2:定义顶层响应包装类(适合长期复用接口场景)

先定义一个和JSON顶层结构匹配的包装类,再直接反序列化整个响应:

  1. 定义包装类
public class RecipeResponse {
    // 字段名和JSON顶层key保持一致,可添加@JsonProperty注解手动指定映射关系
    private List<Recipe> Results;

    // 无参构造方法必须保留
    public RecipeResponse() {}

    public List<Recipe> getResults() {
        return Results;
    }

    public void setResults(List<Recipe> results) {
        Results = results;
    }
}
  1. 执行反序列化
ObjectMapper mapper = new ObjectMapper();
RecipeResponse response = mapper.readValue(json, RecipeResponse.class);
// 拿到菜谱列表
List<Recipe> recipes = response.getResults();
// 若需要数组格式可调用toArray方法转换:Recipe[] recipeArray = recipes.toArray(new Recipe[0]);

额外注意事项

  • Recipe类需要保留无参构造方法,字段名要和单条菜谱的JSON key大小写匹配,不匹配的字段可以添加@JsonProperty("实际JSON字段名")注解指定映射关系。
  • 如果JSON的Results字段可能为null,转换前可以加非空判断避免空指针。

内容的提问来源于stack exchange,提问作者uniqueuser-programmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:48:03