java - 如何从 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 请求中得到的原始文本。
解决方案
试试这个:
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);
推荐阅读
- json - 如何将引用另一个对象的对象转换为 json Asp.net core
- android - Android Studio Gradle Sync 因公司代理失败:找不到有效的证书路径
- jquery - 如果窗口小于 1024 像素,文本锚将不起作用
- json - 无法访问 JSON 获取错误
- c# - 通过将 id 传递给 ashx 从实体框架中的数据库获取图像
- c# - 查找与一个特定 IP 相关的所有 MAC 地址
- javascript - jQuery Wordpress 问题表单验证
- javascript - 返回 Time New Roman 字体而不是 quill 编辑器内容字体
- c# - 如何将文本框中的 XML 格式文本导出到 XML 文件?
- java - 转换为 Maven 项目时 Java Web Socket 不起作用