Jordan Bucholtz Jordan Bucholtz - 1 year ago 80
JSON Question

Parsing JSON in Java Using org.json

I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".

What is the required code to retrieve "bought_together" as a list?

"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "",
"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"]]

Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):

JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));

Answer Source

using the following code, I hope it's help you.

//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


//output is : D202BZX8Z6

-------update according to update the question------ you should change your code like this:

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");


i think you need to this point (it's not technicality all of they difference)

  • every thing are in {} , they will be JSONObject and the relation is key and value like :


    this is a jsonobject and the value of key "name" is ali and we call it like:


  • every thing are in [] ,they will be JSONArray and the relation is index and value like :


    this is a JsonArray the value of index 0 is ali and we call it


so in your case:

  1. your total object is a JSONObject
  2. the value of "related" key is still a JSONObject
  3. the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download