Is it possible to get all the values (linkID,text,options) out of JSON example below (as a String result let's say) using JSONObject, JSONArray, getString() (org.json) library in Java? If yes, can someone please give an example.
"items": [
{
"linkID": "my/link1",
"text": "Some text 1.",
"options": [
"yes",
"no",
"maybe",
"always"
]
},
{
"linkID": "my/link2",
"text": "Some text 2.",
"options": [
"yes",
"no",
"maybe",
"always"
]
}
]
UPDATE:
I found a solution for example above. If there is a better one please tell.
JSONArray items = json.getJSONArray("items");
for (int i = 0; i < items.length(); ++i) {
JSONObject rec = items.getJSONObject(i);
String linkID = rec.getString("linkID");
System.out.println(linkID);
String text = rec.getString("text");
System.out.println(text);
JSONArray options = rec.getJSONArray("options");
System.out.println(options);
}
And can I get inner code that has value 61377 in example below if I have 2 keys with the same names code in JSON payload?
"code": {
"code": "61377",
"result": "ok"
"info": "Some text"
},
Yes, You can get the value of the inner field code by doing this,
jsonObject.optJSONObject("code").optString("code")
Where jsonObject is,
"code": {
"code": "61377",
"result": "ok"
"info": "Some text"
},
Related
Dears,
I am working on creating a simple method which will take String argument which will be a path or other kind "pointer" to attribute/s in JSON and this method will remove those attribute/s.
My problem is I can find values of those attribute/s using JsonPath, but I can't find methods in rest assured (or other libraries) which could remove/delete attributes by given path.
JSON is already added earlier so i need to pull him from RequestSpecification or FilterableRequestSpecification object ex.
RequestSpecification rs = *objFromContext*;
FilterableRequestSpecification frs= (FilterableRequestSpecification) rs;
frs.getBody();
I've tried to work with JSONObject class and remove() but it doesn't work on complex JSONs.
given example JSON
{
"created": "string",
"updated": "string",
"items": [
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value1",
"name": "name",
"value": 123
}
]
},
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value2",
"name": "name",
"value": 123
}
]
}
],
"timer": {
"startDate": "2015-01-01",
"endDate": "2021-01-02"
},
"id": "myId"
}
using JsonPath jp = JsonPath.from(httpRequest.getBody().toString());
and then jp.get(items.itemsproperties.code) i can find value1 and value2.
I stuck in this point: How to remove those attributes from sended body?
I know i can convert body into JSONObject and then go field after field conversion between getJSONArray and GetJSONOBject and remove those fields, but i would like to make this metod much more universal.
Is this possible?
If you want to manipulate json in Rest-Assured JsonPath, then the answer is No. You can't do that. JsonPath help you to extract value from json, that's it, no more.
You have to use different libraries to remove key-value pair.
For example: using JsonPath Jayway
DocumentContext parse = JsonPath.parse(body);
parse.delete("$..itemsProperties..code");
System.out.println(parse.jsonString());
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}
I am aware there are duplicate questions. I am not able to figure this out despite that.
Below is a JSON file which I receive from an API. I need to get the "year" value.
The error I am getting is:
message org.glassfish.jersey.server.ContainerException: org.json.JSONException: JSONArray[1] not found.
Which relates to the line on Java:
JSONObject year = years.getJSONObject(1).getJSONObject("years");
I also tried:
JSONObject year = years.getJSONObject(1);
Why is this code not working? Isn't index 1 clearly year in the years array?
JSON
{
"make": {
"id": 200000404,
"name": "Chevrolet",
"niceName": "chevrolet"
},
"model": {
"id": "Chevrolet_Camaro",
"name": "Camaro",
"niceName": "camaro"
},
"drivenWheels": "rear wheel drive",
"numOfDoors": "2",
"options": [],
"colors": [],
"manufacturerCode": "1EH67",
"price": {
"baseMSRP": 34180.0,
"baseInvoice": 32813.0,
"deliveryCharges": 900.0,
"usedTmvRetail": 17766.0,
"usedPrivateParty": 16321.0,
"usedTradeIn": 14755.0,
"estimateTmv": false,
"tmvRecommendedRating": 0
},
"categories": {
"market": "Performance",
"EPAClass": "Compact Cars",
"vehicleSize": "Midsize",
"primaryBodyType": "Car",
"vehicleStyle": "Convertible",
"vehicleType": "Car"
},
"vin": "2G1FC3D33C9165616",
"squishVin": "2G1FC3D3C9",
"years": [{
"id": 100531911,
"year": 2012,
"styles": [{
"id": 101395591,
"name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)",
"submodel": {
"body": "Convertible",
"modelName": "Camaro Convertible",
"niceName": "convertible"
},
"trim": "LT"
}]
}],
"matchingType": "SQUISHVIN",
"MPG": {
"highway": "28",
"city": "17"
}
}
JAVA
public String vehicleData(#PathParam("vin") String vin,
#PathParam("key") String key) throws Exception {
GetVehicleJSON jsonData = new GetVehicleJSON(vin, key);
JSONObject data = jsonData.getVehicleData();
String name = data.getJSONObject("make").getString("name");
String highway = data.getJSONObject("MPG").getString("highway");
String city = data.getJSONObject("MPG").getString("city");
JSONArray years = data.getJSONArray("years");
JSONObject year = years.getJSONObject(1).getJSONObject("years");
String s = year.getString("year");
return name + " " + s + " " + highway + " " + city;
}
You're working with JSON array whose indexing is zero-based. Do it as:
JSONArray years = data.getJSONArray("years");
String year = years.getJSONObject(0).getString("year");
Your json shows that the years value is an array with 1 element and inside that element is an object:
"years": [{ "id": 100531911, "year": 2012, "styles": [{ "id": 101395591, "name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)", "submodel": { "body": "Convertible", "modelName": "Camaro Convertible", "niceName": "convertible" }, "trim": "LT" }] }],
Because array element numbering begins at 0, that means if you select element 1 you will get this error:
message org.glassfish.jersey.server.ContainerException: org.json.JSONException: JSONArray[1] not found.
To fix it you need to select element 0 instead of 1:
years.getJSONObject(0);
Im requesting data from instagram api when I search for any tag. In return I get a massive chunk of json data corresponding to like 20 pictures. The response below is the chunk I used to generate my pojos online
{
"pagination": {
"next_max_tag_id": "1193052000552992097",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1193052000552992097",
"next_min_id": "1193052554319844057",
"min_tag_id": "1193052554319844057",
"next_url": "https://api.instagram.com/v1/tags/cats/media/recent?access_token=631477962.1fb234f.f7c5cda97c7f4df983b1c764f066ed37&max_tag_id=1193052000552992097"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"cats",
"caseworker",
"homestuck"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1456442969",
"link": "https://www.instagram.com/p/BCOkvoim1LZ/",
"likes": {
"count": 0,
"data": []
},
"images": {
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1456442969",
"text": "Bitch! I'm fabulous! That's my case worker..she is obsessed with cats\n\n#cats #caseworker #homestuck",
"from": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
},
"id": "1193052563471815092"
},
"user_has_liked": false,
"id": "1193052554319844057_2322171747",
"user": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
}
}
So when I do that I get like 10-12 different pojo classes into which I should map this data. Now firstly...Im just trying that out and Im 100% Ill have some problem mapping them I mean gson will do it for me but i dont know if there are any more that I would need etc.
but most importantly my app only needs the low standard url pictures all the other information is useless for me.
Ofcourse, I know one way to do it which is to convert the whole thing into a string and parse the whole string through multiple times looking for key words etc and making images etc. I dont want to do that because its ugly. It works but I want a concise way of doing that at the same time without mapping completely.
Using Gson's JsonParser class, you can parse your JSON into a tree of JsonElements, and then extract just the data that you need.
For example, in order to print out all the low resolution URLs, you could use the following code:
String json = "...";
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(json).getAsJsonObject();
JsonArray data = object.getAsJsonArray("data");
for (JsonElement element : data) {
JsonObject images = element.getAsJsonObject().getAsJsonObject("images");
JsonObject lowResolution = images.getAsJsonObject("low_resolution");
String url = lowResolution.getAsJsonPrimitive("url").getAsString();
System.out.println(url);
}
Using your example JSON, this would print:
https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2