首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用org.json在Java中解析JSON

使用org.json在Java中解析JSON
EN

Stack Overflow用户
提问于 2016-11-07 06:32:35
回答 1查看 10K关注 0票数 1

我有一个包含许多JSON对象的大文件,如下所示。我需要使用org.json library将所有内容解析为数组形式的"bought_together“项。我在访问嵌套在"related“中的任何内容时遇到了问题。

以列表形式检索"bought_together“所需的代码是什么?

代码语言:javascript
复制
{
  "asin": "11158732",
  "title": "Girls Ballet Tutu Zebra Hot Pink",
  "price": 3.17,
  "imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
  "related":
  {
    "also_bought": ["L00JHONN1S", "B002BZX8Z6"],
    "also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
    "bought_together": ["D202BZX8Z6"]
  },
  "salesRank": {"Toys & Games": 211836},
  "brand": "Coxlures",
  "categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}

下面是我的尝试(请注意,这是在MapReduce程序中进行的,因此有些代码行可能看起来不符合上下文):

代码语言:javascript
复制
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-07 06:44:41

使用下面的代码,我希望能对你有所帮助。

代码语言:javascript
复制
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);

//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");

//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");


//now if you run blow code

System.out.print(bought_together.getString(0));

//output is : D202BZX8Z6

-根据更新问题进行更新-你应该这样修改你的代码:

代码语言:javascript
复制
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line

JSONObject related = object.getJSONObject("related");

JSONArray boughtTogether = related.getJSONArray("bought_together");

-更新

我认为你需要做到这一点(这不是技术上的区别,所有的区别都是)

  • 每个东西都在{}中,它们将是JSONObject,关系是键和值,如下所示:

{"name":"ali"}

这是一个jsonobject,key "name“的值是ali,我们这样命名它:

myJsonObject.getString("name");

  • every对象在[]中,它们将是JSONArray,关系是索引和值,如下所示:

“阿里”

这是一个JsonArray,索引0的值是ali,我们称之为

像这样:

myJsonArray.getString(0);

所以在你的例子中:

关键字仍然是JSONObject

  • the值"bought_together“关键字(位于{jsonobject}”相关“关键字的值内) is a JSONArray
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40455305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档