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

Java食谱应用:如何优雅解析Recipe API的JSON响应为对象?

规范解析Recipe API响应的方法

你当前手动截取字符串解析JSON的方式虽然能运行,但存在不少隐患——比如API返回字段顺序变动、字段值包含逗号或引号时,代码直接就会出错,而且后续维护起来特别麻烦。直接用成熟的JSON解析库才是规范简洁的方案,Java里常用的是Jackson和Gson,下面分别给出实现步骤:

第一步:调整你的Recipe类

不管用哪个库,都需要让Recipe类符合JavaBean规范:私有字段+getter/setter方法,再加一个无参构造(Jackson必须要求,Gson建议保留):

public class Recipe {
    private String title;
    private String ingredients;
    private String servings;
    private String instructions;

    // 无参构造,必须保留
    public Recipe() {}

    // 带参构造(可选,方便手动创建对象)
    public Recipe(String title, String ingredients, String servings, String instructions) {
        this.title = title;
        this.ingredients = ingredients;
        this.servings = servings;
        this.instructions = instructions;
    }

    // 所有字段的getter和setter方法
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getIngredients() { return ingredients; }
    public void setIngredients(String ingredients) { this.ingredients = ingredients; }
    public String getServings() { return servings; }
    public void setServings(String servings) { this.servings = servings; }
    public String getInstructions() { return instructions; }
    public void setInstructions(String instructions) { this.instructions = instructions; }

    // 你的自定义print方法
    public String print() {
        return "标题:" + title + "\n食材:" + ingredients + "\n份数:" + servings + "\n做法:" + instructions;
    }
}

方案一:用Jackson解析

Jackson是Spring生态常用的JSON库,稳定性强:

  1. 添加依赖(如果用Maven,在pom.xml中添加):
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 可以使用最新稳定版 -->
</dependency>
  1. 替换解析代码,删掉原来的parseResponse方法,直接用Jackson解析JSON数组:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

class RecipeTest {
    public static void main(String[] args) throws Exception {
        // 发起API请求的代码和之前一致
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://recipe-by-api-ninjas.p.rapidapi.com/v1/recipe?query=chocolate%20chip%20cookies"))
                .header("X-RapidAPI-Key", "myApiKey")
                .header("X-RapidAPI-Host", "theApiHost")
                .GET()
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        String responseString = response.body();

        // 核心解析逻辑:把JSON数组转成List<Recipe>
        ObjectMapper objectMapper = new ObjectMapper();
        List<Recipe> recipeList = objectMapper.readValue(responseString, new TypeReference<List<Recipe>>() {});

        // 测试输出
        for (Recipe recipe : recipeList) {
            System.out.println(recipe.print());
            System.out.println("-------------------");
        }
        System.out.println("共获取到" + recipeList.size() + "份食谱");
    }
}

方案二:用Gson解析

Gson是Google推出的轻量JSON库,上手简单:

  1. 添加依赖(Maven):
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- 最新稳定版 -->
</dependency>
  1. 解析代码:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

class RecipeTest {
    public static void main(String[] args) throws Exception {
        // 请求代码不变
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://recipe-by-api-ninjas.p.rapidapi.com/v1/recipe?query=chocolate%20chip%20cookies"))
                .header("X-RapidAPI-Key", "myApiKey")
                .header("X-RapidAPI-Host", "theApiHost")
                .GET()
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        String responseString = response.body();

        // Gson解析JSON数组
        Gson gson = new Gson();
        List<Recipe> recipeList = gson.fromJson(responseString, new TypeToken<List<Recipe>>(){}.getType());

        // 输出测试
        for (Recipe recipe : recipeList) {
            System.out.println(recipe.print());
            System.out.println("-------------------");
        }
        System.out.println("共获取到" + recipeList.size() + "份食谱");
    }
}

为什么这种方法更好?

  • 健壮性强:自动处理JSON里的特殊字符、字段顺序变化,不会因为API返回格式小改动就报错
  • 代码简洁:几行核心代码完成解析,不用写复杂的索引计算和递归逻辑
  • 易维护:如果API新增字段,只需要给Recipe类加对应的字段和getter/setter就行,解析逻辑不用改

内容的提问来源于stack exchange,提问作者basky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:37:07