首页 > 解决方案 > 如何从 JSON 中的子对象访问内容?

问题描述

我想从以下 JSON 代码中获取“image_url”:

{
  "recipe": {
    "publisher": "Closet Cooking",
    "f2f_url": "http://food2fork.com/view/35382",
    "ingredients": [
      "2 jalapeno peppers, cut in half lengthwise and seeded",
      "2 slices sour dough bread",
      "1 tablespoon butter, room temperature",
      "2 tablespoons cream cheese, room temperature",
      "1/2 cup jack and cheddar cheese, shredded",
      "1 tablespoon tortilla chips, crumbled\n"
    ],
    "source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html",
    "recipe_id": "35382",
    "image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
    "social_rank": 100,
    "publisher_url": "http://closetcooking.com",
    "title": "Jalapeno Popper Grilled Cheese Sandwich"
  }
}

使用 java 中的以下代码,使用“java-json.jar”中的库:

import org.json.JSONException;
import org.json.JSONObject;

JSONObject myResponse = new JSONObject(response.toString());
JSONObject recipe = new JSONObject(myResponse.getJSONObject("recipe"));
ImageURL = recipe.getString("image_url");

我可以创建 JSONObject“recipe”,但是,当执行下一行时,我收到一条错误消息,显示“image_url”未找到。

response 是我从前面的 URL 请求中得到的原始文本。

标签: javajson

解决方案


试试这个:

JSONObject json = new JSONObject(yourJsonString);
System.out.println(json.getJSONObject("recipe").get("image_url"));

这是来自的 JSONObjectimport org.primefaces.json.JSONObject;

这也是你正在做的方法:

JSONObject json = new JSONObject(yourJsonString);
JSONObject json2 = json.getJSONObject("recipe");
String imageUrl = json2.getString("image_url");
System.out.println(imageUrl);

推荐阅读