2.9HarmonyOS NEXT 健康配餐项目实战:项目设计(9)
·
(3)解析 API 响应
Edamam API 返回的响应是 JSON 格式,我们需要解析它。
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Response;
public class NutritionData {
private double calories;
private double protein;
private double fat;
private double carbs;
public NutritionData(double calories, double protein, double fat, double carbs) {
this.calories = calories;
this.protein = protein;
this.fat = fat;
this.carbs = carbs;
}
public static NutritionData fromJson(Response response) throws IOException, JSONException {
String jsonData = response.body().string();
JSONObject json = new JSONObject(jsonData);
JSONObject totalNutrients = json.getJSONObject("totalNutrients");
double calories = json.optDouble("calories", 0);
double protein = totalNutrients.getJSONObject("PROCNT").optDouble("quantity", 0);
double fat = totalNutrients.getJSONObject("FAT").optDouble("quantity", 0);
double carbs = totalNutrients.getJSONObject("CHOCDF").optDouble("quantity", 0);
return new NutritionData(calories, protein, fat, carbs);
}
@Override
public String toString() {
return String.format("Calories: %.2f kcal\nProtein: %.2f g\nFat: %.2f g\nCarbs: %.2f g", calories, protein, fat, carbs);
}
}更多推荐



所有评论(0)