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
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());
Starting from the similar question,
Nested JSON Array in Java
I have a somewhat odd json as a response from a REST api(POST) call. I need to find out the id and name of the sub_items array in each items array element.
I tried like given below for which I am getting error like
org.json.JSONException: JSONObject["items.sub_items"] not found.
I also tried just 'sub_items' as the parameter also, but no. I am using GSON. No choice use others.
final JSONObject jsonObj = new JSONObject(JSON_STRING);
final JSONArray subItems = jsonObj.getJSONArray("items.sub_items");
final int n = subItems.length();
for (int i = 0; i < n; ++i) {
final JSONObject subI= subItems.getJSONObject(i);
System.out.println("id="+subI.getString("id"));
System.out.println("name="+subI.getString("name"));
}
The following is my json as a response from a REST api call.
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
As I said, my JSON is a response from an REST api call, and it is 7300 lines long, like shown below with the outline, as shown in code beautifier.
object {3}
infoTransferReqResp {1}
paramExtens : null
pageGroups {1}
pageGroups [1]
0 {4}
page_group_name : LFG - LG - Insured Summary
page_group_id : 8100
**pages [3]**
repeatingBlocks {1}
I needed to extract a string value 'questionText' from inside 'Pages' array. I used jsonPath() method with navigation path as given below which solved the problem.
JsonPath jsonPathEvaluator = response.jsonPath();
List<List<List<String>>> questions = jsonPathEvaluator.getList("pageGroups.pageGroups.pages.questions.questionText");
It gave me 3 ArrayLists one embedded in another corresponding to 3 arrays of 'pages'
I am unable to parse this JSON file.
Any suggestions are appreciated. I have created POJO classes from http://www.jsonschema2pojo.org/ I tried JSON deserilization solution mentioned but it did not work out for me.
{
"error": "",
"data": [
{
"view": "Viewpapger",
"data": [
{
"view": "ImageView",
"data": {
"url": "random.jpg"
},
"properties": {
"width": "fill_parent",
"height": "500"
}
},
{
"view": "Textview",
"data": {
"text": "afvnjkafvf"
},
"properties": {
"width": "fill_parent"
}
},
{
"view": "Textview",
"data": {
"text": "afvnjkafvf"
},
"properties": {
"width": "fill_parent"
}
},
{
"view": "ImageView",
"data": {
"url": "random.jpg"
},
"properties": {
"width": "fill_parent",
"height": "500"
}
}
],
"properties": {
"width": "wrap_content",
"height": "500"
}
},
{
"view": "Textview",
"data": {
"text": "afvnjkafvf"
},
"properties": {
"width": "fill_parent"
}
},
{
"view": "ImageView",
"data": {
"url": "random.jpg"
},
"properties": {
"width": "fill_parent",
"height": "500"
}
}
]
}
I think the problem here is that the JSON structure does not correspond to any strictly specified schema but seems more like an ad-hoc collection of keys and values. For example, (it seems that) depending on the value of the view field in your view description object the data field can be either
a JSON array containing other view descriptions (for "Viewpager")
a JSON object containing a string called "url" (for "ImageView")
a JSON object containing a string called "text" (for "TextView")
So, basically it seems that data can be anything and moreover that you could have an arbitrarily deep tree of nodes where data could be anything at any level in the tree. (It may be different though if, for example, you can always be certain that the top level element is a "Viewpager" that contains one level of sub-views like "ImageView" or "TextView" - if you have any guarantees like that let me know).
In that case I think you are better off parsing the JSON in some other, less strict way (maybe using org.json.JSONArray and org.json.JSONObject) and then handling all the different cases "manually".
I am developing first time in android and i have never used json data before. I will develop an application of event calendar of my university. We developed web version application in Django and we implement tastypie (restapi) so i need to use this json data for android mobile version. My json data is like this :
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 5
},
"objects": [{
"Location": "Z011",
"Notes": "asdf",
"Title": "Literature Talking",
"id": 3,
"resource_uri": "/api/v1/Events/3/"
}, {
"Location": "Batı Kampüsü, Sinema Salonua",
"Notes": "sd",
"Title": "TARİHÇE KONFERANSLARI SERİSİ 25",
"id": 4,
"resource_uri": "/api/v1/Events/4/"
}, {
"Location": "in Campus",
"Notes": "afafdf",
"Title": "Self-Assessment Project",
"id": 5,
"resource_uri": "/api/v1/Events/5/"
}, {
"Location": "Kütüphane",
"Notes": "fs",
"Title": "51.Kütüphane Haftası",
"id": 6,
"resource_uri": "/api/v1/Events/6/"
}]
}
how can I parse this Json data in android studio?
Using below code you will be able to get Title and Location
JSONObject obj=new JSONObject(response);//This is response from webservice
String totalCount = obj.getJSONObject("meta").getString("total_count"); //for getting total_count
JSONArray json_array = obj.getJSONArray("objects");
for(int j=0;j<json_array.length();j++) {
String title = json_array.getJSONObject(j).getString("Title");
String location= json_array.getJSONObject(j).getString("Location");
}
Use this website to help you view the Json structure better
http://www.jsontree.com/
What you have is a Json Object since it starts and ends with curly braces.
For example if I had a Json as {"Id":"1"}
The Key is "Id" and the value is "1"
A Json object can have a Json inside the value as well(Which is your case)
And example is {"Id":{"Place1":"1", "Place2":"2"}}
So the Key is "Id" and it has the value "Place1":"1", "Place2":"2"
So the value is also a Json.
It can get a little messy with Jsons in Jsons.
Here is a good tutorial on parsing Json
http://www.tutorialspoint.com/android/android_json_parser.htm
I have this Bing Maps JSON file and I want to retrieve "++formattedAddress++" from inside it
{
"statusCode": 200,
"statusDescription": "OK",
"copyright": "Copyright © 2013 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"authenticationResultCode": "ValidCredentials",
"resourceSets": [
{
"resources": [
{
"__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
"point": {
"type": "Point",
"coordinates": [
63.8185213804245,
12.105498909950256
]
},
"matchCodes": [
"Good"
],
"address": {
"addressLine": "55 Stuff",
"locality": "Stuff",
"++formattedAddress++": "55 Stuff, 51512 Stuff",
"postalCode": "25521",
"adminDistrict2": "Stuff-Stuff",
"countryRegion": "UK",
"adminDistrict": "NL"
},
"bbox": [
84.81465866285382,
12.097347537264563,
50.822384097995176,
7.11365028263595
],
"name": "55 Stuff, 51122 Stuff",
"confidence": "Medium",
"entityType": "Address",
"geocodePoints": [
{
"calculationMethod": "Interpolation",
"type": "Point",
"usageTypes": [
"Display",
"Route"
],
"coordinates": [
50.8185213804245,
7.105498909950256
]
}
]
}
],
"estimatedTotal": 1
}
],
"traceId": "8a13f73cab93472db1253e4c1621c651|BL2M002306|02.00.83.1900|BL2MSNVM001274, BL2MSNVM003152",
"brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png"
}
What I have tried so far is like this:
final JSONArray jsonMainArr = locationData.getJSONArray("resourceSets").getJSONObject(0).getJSONArray("resources");
final JSONObject childJSONObject = jsonMainArr.getJSONObject(0);
return childJSONObject.getString("formattedAddress");
childJSONObject is still 2-3 levels over formattedAddress and the query is becoming highly inefficient
get formattedAddress address value as from current json String :
final JSONObject childJSONObject = jsonMainArr.getJSONObject(0)
.getJSONObject("address");
return childJSONObject.getString("++formattedAddress++");
There are so much online sites where you paste your complex code and get it in an easy way. e.g. http://json.parser.online.fr/