java 将HttpResponse从API解析为对象

62lalag4  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(151)

我正在开发一个Recipe应用程序,处于早期阶段。我以前从未使用过API,但我对它有了基本的了解,我已经做了很多搜索,以达到这一步,但基本上是这样的:我使用的是RapidAPI的Recipe API,它可以返回多个响应。我想把所有的响应解析到我的Recipe类的对象中。我已经得到了代码的工作和功能,但我觉得必须有一个更好的方式来完成我正在试图做的事情。我目前正在使用一个函数将String解析为Recipe对象的ArrayList,使用TryCatch块在遇到索引越界异常时终止。
Rapid API发送信息的方式是字符串格式,但每个配方都包含在自己的{花括号}中,所以我想知道是否有一些方法可以在考虑到这一点的情况下操作数据(也许是用数组的东西?),但还没弄清楚任何事情。无论如何,我将包括我的代码,我也将包括什么是从API返回的示例。
responseString看起来像这样

[{"title": "Recipe 1", "ingredients": "blah", "instructions": "blah"}, {"title": "recipe 2", etc}]
class RecipeTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        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")
                .method("GET", HttpRequest.BodyPublishers.noBody())
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        String responseString = response.body();

        List<Recipe> recipeList = parseResponse(new ArrayList<Recipe>(), responseString.replaceAll("\"", ""), 0);

        System.out.println(recipeList.get(0).print());
        System.out.println(recipeList.get(1).print());
        System.out.println(recipeList.get(2).print());
        System.out.println(recipeList.size());

    }

    static List<Recipe> parseResponse(ArrayList<Recipe> recipes, String s, int begin) {

        try {
            int titleBeginIndex = s.indexOf("title:", begin);
            int titleEndIndex = s.indexOf(",", titleBeginIndex);

            int ingredientsBeginIndex = s.indexOf("ingredients:", titleEndIndex);
            int ingredientsEndIndex = s.indexOf(",", ingredientsBeginIndex);

            int servingsBeginIndex = s.indexOf("servings:", ingredientsEndIndex);
            int servingsEndIndex = s.indexOf(",", servingsBeginIndex);

            int instructionsBeginIndex = s.indexOf("instructions:", servingsEndIndex);
            int instructionsEndIndex = s.indexOf("}", instructionsBeginIndex);

            String title = s.substring(titleBeginIndex, titleEndIndex);
            String ingredients = s.substring(ingredientsBeginIndex, ingredientsEndIndex);
            String servings = s.substring(servingsBeginIndex, servingsEndIndex);
            String instructions = s.substring(instructionsBeginIndex, instructionsEndIndex);

            recipes.add(new Recipe(title, ingredients, servings, instructions));

            parseResponse(recipes, s, ingredientsEndIndex);
        } finally {
            return recipes;
        }
    }
}

我只是在寻找一种更简洁的方法来解析配方对象数组或列表中的数据。我的尝试...最后块工作,但我觉得我没有这样做的正确方式。

e37o9pze

e37o9pze1#

有一些工具可以帮助你pares json字符串,如JacksonGson
我用Jackson写了一个示例代码,希望对你有帮助.
要了解更多使用Jackson的方法,您需要自己学习。

public static void main(String[] args)  throws Exception{
    String responseString = "[{\"title\": \"Recipe 1\", \"ingredients\": \"blah\", \"instructions\": \"blah\"}, {\"title\": \"recipe 2\"}]";
    List<Recipe> recipeList = parseResponse( responseString);
    for (Recipe recipe : recipeList) {
        System.out.println(recipe);
    }
}

static List<Recipe> parseResponse( String s )  {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(s, new TypeReference<List<Recipe>>() {
        });
    }catch (Exception e) {
        e.printStackTrace();
    }
    return new ArrayList<>();

}
static class Recipe{
    String title;
    String ingredients;
    String servings;
    String instructions;

    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;
    }

    @Override
    public String toString() {
        return "Recipe{" +
                "title='" + title + '\'' +
                ", ingredients='" + ingredients + '\'' +
                ", servings='" + servings + '\'' +
                ", instructions='" + instructions + '\'' +
                '}';
    }
}

相关问题