I'm trying to parse this (for example) :
"id":"54f49b4a98686d9478ae44f5",
"title":"Free books",
"slug":"free-books",
"modules":[
[
"list",
{
"slug":"gutenberg",
"title":null,
"books":[]
}
]
]
}
How can i get the "books" array ? I use volley library.
Thanks
You can use JSONArray. Supposing you have a JSONObject called response you can get the books as following:
JSONArray modules = response.getJSONArray("modules");
JSONObject object = modules.getJSONObject(1);
JSONArray books = object.getJSONArray("book");
Take a look here in order to use it with Volley: http://www.androidhive.info/2014/09/android-json-parsing-using-volley/
Related
I have recently moved to test API's for a new project with Rest Assured. I am not so fluent in Java, so that is why I need to know how to optimise the code.
Let's say I have an API, which output's JSON in this format -
{
"records":[
0: {
"id" : 1232,
"attribute1": "some_value",
"attribute2": "some_value1"
},
1: {
"id" : 1233,
"attribute1": "some_new_value",
"attribute2": "some_new_value1"
}]}
There are around 400 such objects coming inside the records array. I want to get the id of all the 400 records, and store in an array. I am able to do so, but I think the approach can be optimised.
My current code :
private static Response response;
Response r;
JSONParser parser = new JSONParser();
String resp = response.asString();
JSONObject json = (JSONObject) parser.parse(resp);
JSONArray records= ((JSONArray)json.get("records"));
ArrayList<Long> idlist = new ArrayList<Long>();
for(int i=0;i<records.size();i++) {
idlist.add((Long) ((JSONObject)records.get(i)).get("id"));
}
How can I minimize the lines of code to achieve the same thing?
Response response
// Code that assigns the response
List<Long> idList = response.jsonPath().getList("records.id");
// Code that uses the id list.
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
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.
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.
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.