Parsing JSON in Java Using org.json - java

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": "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"]]
}
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"));

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
System.out.print(bought_together.getString(0));
//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");
-------update-------
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 :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray

Related

JAVA: Save data in JSON [duplicate]

This question already has answers here:
JSONObject : Why JSONObject changing the order of attributes [duplicate]
(3 answers)
Closed 7 years ago.
When you add data in JSONObject it will store in it's own way.
Here is the Example of what i am trying to convey.
JSONObject obj = new JSONObject();
obj.put("metricname", "splunk-ui");
obj.put("timestamp", 1234567890);
obj.put("value",34);
System.out.println(obj);
Above code snippet will give below output.
{
"metricname": "splunk-ui",
"value": 34,
"timestamp": 1234567890
}
Here is the Problem :-
I add data in this sequence :- metricname , timestamp , value
This is the display sequence :- metricname , value , timestamp
So , how do i enforce my data adding sequence in JSONObject ??
FYI :- Doing this is mendatory as i will pass this JSON object to another API which can scan data in metricname , timestamp , value only.
HERE I AM POSTING CODE SNIPPET WHICH I USED FOR SOLVING THIS PROBLEM :-
I have used GSON library and this link to make this code work.
GSON Documention
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("metric", "mihirmonani");
jsonObject.addProperty("timestamp", 1346846400);
jsonObject.addProperty("value", 14);
JsonArray jArray = new JsonArray();
JsonObject jObject = new JsonObject();
jObject.addProperty("host", "splunk");
jObject.addProperty("host1", "splunk1");
jsonObject.add("tags",jObject);
System.out.println(jsonObject);
You can't with a JSONObject the only way to keep the order is using a JSONArray
[
{"name" : "metricname", "value" : "splunk-ui"},
{"name" : "value", "value" : 34},
{"name" : "timestamp", "value" : 1234567890}
]
Short answer: you can't. JSONObject uses a HashMap internally, which returns values depending on the order of the hash code.
You could use JSONWriter to write the values explicitly.
EDIT: To clarify, as Manu pointed out, you cannot retrieve the order after the values have been put in the JSONObject. My suggestion was to not put the values in the JSONObject to begin with, but use JSONWriter to write the values directly.

Create JSON Array from List<Object> in Java

This is a basic Java question I think that I can't work out how to get around.
I get data from Google Analytics API and store the rows in my database as a string as a JSONArray
[["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]]
For Google Maps I need a JSON Array:
function drawMap() {
var data = google.visualization.arrayToDataTable([
['City', 'Popularity'],
['New York', 200],
['Boston', 300],
['Miami', 400],
['Chicago', 500],
['Los Angeles', 600],
['Houston', 700]
]);
From https://developers.google.com/chart/interactive/docs/gallery/geomap
I need to change my data, by parsing it and iterating through it to remove the first (i.e. "New Zealand") and last variable from each object - I also need to add the headers i.e. ['City', 'Popularity']
Using GSonBuilder I can create JSON
[{"city":"Wellington","sessions":"1314","viewsPerSessions":"8.428462709284627","avgDuration":"8.428462709284627"},{"city":"Christchurch","sessions":"432","viewsPerSessions":"10.127314814814815","avgDuration":"10.127314814814815"}]
How do I turn that into a JSON Array?
I use the JSON parse of Android. With this you can get what you want.
Try this:
JSONArray js_data = [["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]];
int lenght = js_data.length();
JSONArray city;
for(int i=0;i<length;i++) {
//get each city
city = js_data.getJSONArray(i);
String nameCity = city.getString(0);
String pop = city.getString(4);
//Create a object JSON or whatever you want with this data
JSONArray js_array = new JSONArray();
js_array.put(city); js_array.put(pop);
//And put on a list
js_map.put(js_array);
}
This is a basic java coding.
Hope it's helps.

Jettison JSON/java , send list of string with json request

I am creating JSON object and send over the network , like
org.codehaus.jettison.json.JSONObject json = new org.codehaus.jettison.json.JSONObject();
json.put("id", "15");
json.put("code", "secret");
json.put("type", "new type");
Also I have links of photos what I want to put into this JSON
my links like http://box.com/images/photo.jpg,http://box.com/images/photo1.jpg
http://box.com/images/photo2.jpg, http://box.com/images/photo3.jpg
As I understand I must have some list/array and put like
json.put("images", links)
How to do it, put and parse... I need one key, and list of values.
Is JSON array is useful for this?
Thanks
Yes. JSONArray is what you need.
List <String> links = getLinks();
JSONArray array = new JSONArray();
for (String link : links)
array.put(link);
JSONObject obj = new JSONObject();
//put id, code, type...
obj.put("images", array);
Check out the JSONArray class.
http://jettison.codehaus.org/apidocs/org/codehaus/jettison/json/JSONArray.html
You'll create a JSONArray and use that in your put command.

JSONObject in JSONObject

I have an API Output like this:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject from this API with:
JSONObject json = getJSONfromURL(URL);
After this I can read the data for User like this:
String user = json.getString("user");
But how do I get the Data for stat1 and stat2?
JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).
Given your JSON, you'd need to do something like this:
JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");
Note the lack of error handling here: for instance the code assumes the existence of the nested members - you should check for null - and there's no Exception handling.
JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");
from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.
To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:
var star1 = user.stat1;
Using Google Gson Library...
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
//
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
If You have any doubts , Please let me know in comments ...

How to parse this JSON string

I'm trying to parse this string into java, but I keep getting errors.
{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}
When I use this code ...
String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");
I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?
The array named "sources" is several levels deep. You need to traverse down into the json.
Code formatters help with this stuff...
http://jsonformatter.curiousconcept.com/
{
"id":1,
"jsonrpc":"2.0",
"result":{
"limits":{
"end":3,
"start":0,
"total":3
},
"sources":[
{
"file":"/media/storage/media/re Music/",
"label":"re Music"
},
{
"file":"/media/storage/media/ra Music/",
"label":"ra Music"
},
{
"file":"addons://sources/audio/",
"label":"Music Add-ons"
}
]
}
}
It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:
JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");
Your json should have top level object, from there you need to get child objects. See this link for more detail.

Categories