parsing json in android studio - java

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

Related

Failure to parse this json field

I can get other fields correctly, but can parse the "title" or "title_full" values. I always receives an empty string. I am using the org.json library. This is the json. What's the trick?
try {
title = jsonDoc.getString("title_full");
} catch (JSONException e) {
log.info("no full title: " + docString);
}
{
"organizations": [],
"uuid": "d0adc516c9012113774557365f9847da99b228e7",
"thread": {
"site_full": "www.fark.com",
"main_image": "http://img.fark.net/images/cache/orig/5/51/fark_514Jh7VFpynQw4MyN2xcK1jwCxk.png?t=RQrnhq8EGZiUuElMitgLOQ&f=1488776400",
"site_section": "http://www.fark.com/discussion/",
"section_title": "FARK.com: Discussion links",
"url": "http://www.fark.com/comments/9500577/I-want-to-support-work-that-NY-Times-Washington-Post-are-doing-I-can-only-afford-one-subscription-Who-do-you-recommend-I-throw-my-support-to?cpp=1",
"country": "US",
"domain_rank": 3382,
"title": "(9500577) I want to support the work that the NY Times and Washington Post are doing. I can only afford one subscription. Who do you recommend I throw my support to?",
"performance_score": 0,
"site": "fark.com",
"participants_count": 31,
"title_full": "FARK.com: (9500577) I want to support the work that the NY Times and Washington Post are doing. I can only afford one subscription. Who do you recommend I throw my support to?",
"spam_score": 0.0,
"site_type": "discussions",
"published": "2017-03-03T12:00:00.000+02:00",
"replies_count": 2,
"uuid": "67213179a24931106e75cd588386bd30fb3bbdc8"
},
"author": "EbolaNYC",
"url": "http://www.fark.com/comments/9500577/I-want-to-support-work-that-NY-Times-Washington-Post-are-doing-I-can-only-afford-one-subscription-Who-do-you-recommend-I-throw-my-support-to?cpp=1#c107765048",
"ord_in_thread": 1,
"title": "",
"locations": [],
"entities": {
"persons": [],
"locations": [],
"organizations": []
},
"highlightText": "",
"language": "english",
"persons": [],
"text": "dionysusaur : Either the NY Post or the WA Times.\nOnly asshats read the NY Post.",
"external_links": [],
"published": "2017-03-03T15:58:00.000+02:00",
"crawled": "2017-03-03T17:05:26.049+02:00",
"highlightTitle": "",
"social": {
"gplus": {"shares": 0},
"pinterest": {"shares": 0},
"vk": {"shares": 0},
"linkedin": {"shares": 0},
"facebook": {"likes": 0, "shares": 0, "comments": 0},
"stumbledupon": {"shares": 0}
}
}
Your JSON seems like follows:
{
{
"main": {
"key": "value",
},
},
}
So, First fetch the main json and then the key.
Code should be like as follows:
String something = jsonDoc.get("main").get("key").toString();
There are two title values in your JSON, Do check which title you need before fetching.
After I formatted the json code, the problem becomes obvious:
title_full is only available inside the thread node, and a non-empty title is also only inside the thread node. So you'll first have to access the thread node and then access title and title_full inside that node.
Using the org.json library, you can access the fields like this:
String fullTitle = jsonDoc.getJSONObject("thread").getString("title_full");
If you take a look at the json you will see that the "title" and "title_full" fields are in the thread field.
So try reading that field and then parsing the filed into a new jsonObject and you should be able to get them.

Navigating through JSONObject Android

I am trying to implement a method which is able to navigate through a JSONObject until it finds a given parameter. My JSON is structured like a foldersystem. There are folders and every folder can have files.A folder can have another folder and so on.JSON is looking like this:
{
"Elements": [
{
"file": {
"files": [
{
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"modified": 1457608018166,
"name": "Bild1"
},
{
"id": "0efd76e7-730e-428a-96a4-95e04844070a",
"modified": 1457608018166,
"name": "Audio"
},
{
"files": [
{
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"modified": 1457608018166,
"name": "Bild2"
},
{
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"modified": 1457608018166,
"name": "Bild3"
},
{
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"modified": 1457608018166,
"name": "Bild4"
}
],
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"name": "FolderInRoot"
}
],
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"name": "RootFolder"
}
},
{
"file": {
"files": [],
"id": "562dd7a2-9268-46b2-8963-b7a3b43e906e",
"name": "AnotherRootFolder"
}
}
]
}
So for example I want to edit "Bild2" which has the path "/RootFolder/FolderInRoot/Bild2". Has someone a method which navigates to that given position. The path should be the parameter.
You need to loop through the your JSON response until you get to the correct depth, and then you can use getString("name") to get the content at that key (i.e. Bild2). Once you get the content from the object/key you can add it to a List or Map to iterate over or do anything else you want with the data. See this StackOverflow question for more info: Java loop over Json array?
You also might want to consider using the Gson library to make your parsing a lot easier. If you are able to add Gson to the project (and I suggest that you do), there are a ton of great tutorials for parsing data and deserializing JSON into plain Java objects (which will save you the headache of nested loops). Using GSON in Android to parse a complex JSON object and http://blog.nkdroidsolutions.com/how-to-parsing-json-array-using-gson-in-android-tutorial/ are two good resources to begin with.
(P.S. you might want to consider simplifying your JSON structure if possible because it will be a lot easier to work with).

How to get specific bits of json response effectively?

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

Most memory efficient way to re format a JSON array in Java

Say I have a JSON array similar to the following:
[
{
"title": "This is a title",
"year": 2013,
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
"thumbsdown": 256
}
},
{
"title": "This is a title",
"year": 2013,
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
"thumbsdown": 256
}
}
]
And the required output is a JSON array like this:
[
{
"title": "This is a title",
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
}
},
{
"title": "This is a title",
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
}
}
]
Iv'e been researching and it's suggested that the most efficient way would be to parse it using the Jackson streaming API. This is for use on a PaaS with limited memory, so I wish to keep the memory usage to the bare minimum.
Is the best way to parse the JSON with Jackson Streaming API, and construct a new JSON array at the same time or simply remove the elements somehow?
I did something similiar with XML once. You can have the requestor tell you what fields you want to get back, and have it only emit those. In my case I had no control over the 3rd party axis xml view, but once I had the view, when I asked for things from it if it was already there I could give back just the pieces I was interested in. As a bonus, if you are marshalling or unmarshalling real java objects from the JSON after getting the json or XML you don't need to build the part of the object graph you don't care about.

Displaying JSON in a ListView with separators

I want to be able to take the JSON data and format it into a ListView with each of the outermost objects as the headings. For example, there should be a divider for "Company A" and all of its projects under the divider. Then there should be the "Company B" divider and it's project under that header. Here's an example of a JSON response I'll be working with. I know how to parse the JSON, just not how to display it.
{
"Company A": {
"name": "Company A",
"id": "1145",
"projects": [
{
"name": "Test Project - DELETE",
"id": "39771",
"amount": "0.00",
"billingType": "HOURLY",
"date": "2012-07-09 15:38:06",
"u_id": "25445",
"itemID": "3"
},
{
"name": "TEST",
"id": "39905",
"amount": "0.00",
"billingType": "FIXED",
"date": "2012-07-10 13:19:10",
"u_id": "25455",
"itemID": "1"
},
{
"name": "Test Project - DELETE",
"id": "39771",
"amount": "0.00",
"billingType": "HOURLY",
"date": "2012-07-09 15:38:06",
"u_id": "25445",
"itemID": "4"
}
]
},
"Company B": {
"name": "Company B",
"id": "5569",
"projects": [
{
"name": "Type Test",
"id": "39657",
"amount": "0.00",
"billingType": "FIXED",
"date": "2012-07-12 10:14:30",
"u_id": "25479",
"itemID": "1"
}
]
}
}
Is there an easy way to achieve this kind of formatting?
Yes and no.
You can easily convert each set (header with content) into an object, and the content itself into sub-objects (if you need help, ask :)); the hard part is configuring the ListView if you aren't familiar with using multiple item types.
I think the answer to this question will be of use to you.
To summarize: basically, ListView can be made to use multiple item types; so your header would be one item type and each data item would be of a second type. Just implement the glue logic so that you get the right view type for the right object, and the right object for the right ListView "position".

Categories

Resources