How to get a particular object from JSON array [Android] [duplicate] - android

This question already has answers here:
How to parse JSON in Kotlin?
(17 answers)
Closed 3 years ago.
I have a response json like this,
[{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
},
{
"userId": 2,
"id": 2,
"title": "sunt qui excepturi placeat culpa"
},
{
"userId": 3,
"id": 3,
"title": "omnis laborum odio"
}]
I want to show detail from userId = 3, I wasn't provided an endpoint to get detail. So I want to get detail from this endpoint.
in App:
I've shown the data for dashboard (using recyclerview/list)
After that, I want to go to detail from one data that I selected.
Case: I'm using 1 endpoint (like above)

JSONArray jsonArray = (JSONArray) JSON.parse(str);
Map map = jsonArray.stream().map( obj -> {JSONObject jsonobject = (JSONObject) obj;return jsonobject;}).collect(Collectors.toMap(obj->obj.getIntValue("userId"),obj->obj.toJSONString()));
System.out.println(map.get(3));

the start point of json must always be a jsonObject not jsonArray. head to your backend developer and ask him or her to put your jsonArray inside a jsonObject.
{
"docs":[{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
},
{
"userId": 2,
"id": 2,
"title": "sunt qui excepturi placeat culpa"
},
{
"userId": 3,
"id": 3,
"title": "omnis laborum odio"
}]
}

Related

Getting LARGE nested Json from NYT API

I'm trying to use the New york times api to show the headline and an image in a listview on android. I'm already getting the data for headline and date and outputting to log cat. The real problem is: whenever I put the extra field to get the mulimedia (images url) the "GC_FOR_ALLOC freed 1902K (64), 22% free 11931K/15156K" is shown
I've seen that the api always sends fixed number of 10 nyt articles, but each of the 10 has a multiple multimedia urls and json with arrays nested and the app freezes. I'll learn to put the data on listview on my own, my real question is, whats the best approach to fix the crash, I only want 1 url image per article.
//THE RETURNED JSON WITH ONLY "MULTIMEDIA" FIELD QUERY.
{
"status": "OK",
"copyright": "Copyright (c) 2018 The New York Times Company. All Rights
Reserved.",
"response": {
"docs": [
{
"multimedia": [
{
"rank": 0,
"subtype": "xlarge",
"caption": null,
"credit": null,
"type": "image",
"url": "images/2018/09/07/opinion/07Parcak/merlin_143215881_20cecc31-7c8d-4b8f-8541-773170c1822c-articleLarge.jpg",
"height": 400,
//MORE CODE HERE.. THEN NEXT ARRAY BELOW
{
"multimedia": [
{
"rank": 0,
"subtype": "xlarge",
"caption": null,
"credit": null,
"type": "image",
"url": "images/2018/09/03/world/03xp-brazil-promo/03xp-brazil-promo-articleLarge.jpg",
"height": 400,
"width": 600,
"legacy": {
"xlarge": "images/2018/09/03/world/03xp-brazil-promo/03xp-brazil-promo-articleLarge.jpg",
"xlargewidth": 600,
"xlargeheight": 400
},
"subType": "xlarge",
"crop_name": "articleLarge"
},
// Goes on forever.
What do you use to get the data, what kind of REST client are you using?
For example if you are parsing the response by yourself you can put some logic like
JSONObject obj = new JSONObject(" .... ");
JSONArray arr = obj.getJSONArray("multimedia");
JSONObject firstMultimedia = null;
if (arr.length() > 0){
firstMultimedia = arr.getJSONObject(0);
}

Parse Nested JSON data in Android

I am trying to parse JSON data which looks like this in android;
{
"data": [{
"http_code": 200,
"message": "success",
"created_at": "2016/10/12",
"categories": [{
"cat_id": 1,
"cat_name": "Business and Commerce",
"subcategories":[{
"subcat_id": 1,
"subcat_name": "Intellectual Property",
"articles":[{
"article_id": 1,
"article_heading": "What is intellectual?",
"article_url": "http://example.com/1"
},{
"article_id": 2,
"article_heading": "Types of intellectual Properties",
"article_url": "http://example.com/2"
}]
}, {
"subcat_id": 2,
"subcat_name": "Business Licensing",
"articles":[{
"article_id": 1,
"article_heading": "What is a license?",
"article_url": "http://example.com/1"
},{
"article_id": 2,
"article_heading": "Types of Business Licenses",
"article_url": "http://example.com/2"
}]
}]
}, {
"cat_id": 2,
"cat_name": "Family Law",
"subcategories":[{
"subcat_id": 3,
"subcat_name": "Domestic Violence",
"articles":[{
"article_id": 1,
"article_heading": "What is domestic violene?",
"article_url": "http://example.com/1"
},{
"article_id": 2,
"article_heading": "Types of domestic violence",
"article_url": "http://example.com/2"
}]
}, {
"subcat_id": 4,
"subcat_name": "Marriage",
"articles":[{
"article_id": 1,
"article_heading": "What is a marriage?",
"article_url": "http://example.com/1"
},{
"article_id": 2,
"article_heading": "Types of marriages",
"article_url": "http://example.com/2"
}]
}]
}]
}]
}
I am supposed to see data for a specific node when I select it via a listview list item click and so on....
So far I have managed to parse all the categories and display them in a listview, but I want to display subcategories for a category I select on the listview.
Set an onItemClickListener on your listview and use the position of the selected item to return the relevant subcategories?
For example, perhaps something along the lines of:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Switch(position) {
case 0:
//get first subcategories array values
break;
case 1:
//get second subcategories array values
break;
....
}
}
Use ExpandableListView, example given on this link.
For json parsing use Google gson, it will make your work easy and efficient.
It seems similar to How to parse this nested JSON array in android
But you can use this lib https://github.com/FasterXML/jackson
to make the work easy and faster using Objects.
It is a small tutorial: JacksonInFiveMinutes
Specially: Full Data Binding (POJO) Example. And JacksonDataBinding
Thanks everyone for your help. I finally managed to solve the issue;
Here is how I did it;
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject subcategories = jsonObj.getJSONObject("data").getJSONArray("categories").getJSONObject((int)getItemId(position));
Log.e("TAG","Subcategories: " + subcategories);
I don't know if that is the correct way, but it worked in my case.

Adding Data in Firebase Database

I am migrating to Firebase to help me retrieve my data. My question is how can I format my Firebase Database data like the JSON below. How can I specify objects like the JSON below?
[
{
"DoctorsName": "DR.LUTAAYA HUZAIFAH IDRIS",
"HealthCentreName": "Mulago",
"Specialisation": "Dentist",
"Information": "am genious",
"photo": "huzaifah.jpg",
"WorkingHours": "8:00am - 3:00pm",
"PhoneNumber": "0704594180",
"Email": "huxaiphaeridris#gmail.com"
},
{
"DoctorsName": "DR. G. WABULEMBO",
"HealthCentreName": "Kibuli",
"Specialisation": "Opthalmologist",
"Information": " is a consultant Opthalmologist with over 25 years experience in Canada and Uganda.",
"photo": "wabulembo.jpg",
"WorkingHours": "8:00am - 12:00pm",
"PhoneNumber": "0756478923",
"Email": "wabulembo#gmail.com"
},
{
"DoctorsName": "DR. BUKIRWA JAUHARAH",
"HealthCentreName": "Kibuli",
"Specialisation": "Urologist",
"Information": "Shes a Urologist , she has an experience of 7 years in Kibuli Hospital , and she studied in the United States Of America University",
"photo": "jauharah.jpg",
"WorkingHours": "10:00am - 4:00pm",
"PhoneNumber": "0706081457",
"Email": "bukijauha#gmail.com"
},
{
"DoctorsName": "DR. R. SEKITOLEKO",
"HealthCentreName": "Nakasero Hospital",
"Specialisation": "General Physician",
"Information": " is consultant physician with over 33 years of experience in Berlin and Hamburg (Germany) and Mulago Hospital (Uganda). He also practised as a consultant with WHO (2001-2003).",
"photo": "sekitoleko.jpg",
"WorkingHours": "12:00am - 7:00pm",
"PhoneNumber": "0765633667",
"Email": "sekitoleko#gmail.com"
},
{
"DoctorsName": "DR. A. MAKHOBA ",
"HealthCentreName": "Nakasero Hospital",
"Specialisation": "Cardiologist",
"Information": "is a consultant cardiologist,. He has practised for more than 20 years in Illinois and Wisconsin (USA) and for over two years in Uganda, at the Uganda Heart Institute and Nakasero Hospital.",
"photo": "makhoba.jpg",
"WorkingHours": "8:00am- 4:00pm",
"PhoneNumber": "0765453636",
"Email": "makhoba#gmail.com"
},
{
"DoctorsName": "DR.Sako Banabus",
"HealthCentreName": "Nakasero Hospital",
"Specialisation": "Dentist",
"Information": null,
"photo": "kamanzi.jpg",
"WorkingHours": "7:00pm - 3:00am",
"PhoneNumber": "0754369696",
"Email": "sw#gmail.com"
},
{
"DoctorsName": "DR. KAMANZI ABUBAKAR",
"HealthCentreName": "Mengo Hosiptal",
"Specialisation": "Neurosurgeon",
"Information": "Hes a Neurosurgeon, he has an experience of 20 years in Mengo Hospital , he studied in the Carlifornia University",
"photo": "kamanzi.jpg",
"WorkingHours": "7:00pm - 3:00am",
"PhoneNumber": "07003014850",
"Email": "kamanziabubakar75#gmail.com"
}
]
You can write pretty much any JSON you'd like directly to Firebase. For ease of retrieval though, you'd need to figure out some sort of schema. I'd recommend something like the following:
doctors
<docotrId>
- doctorId
- doctorName
- specialisation
- information
- photo
- phone
- email
- #healthCenter
healthCenters
<healthCenterId>
- centerId
- name
- #doctors[]
specialisationDoctors
<specialisationName>
<doctorId>
The first thing you need to do is map your data to this schema. You can create POJO classes, Maps, or even JSON formatted strings.
Then push your mapped data using setValue() on the appropriate nodes. Make sure to read the documentation for more information.
You might also want to check out a Firebase object mapper I'm working on called Firebomb (shameless plug). The Android version will be coming soon.
Finally retrieve data by using the appropriate Firebase event listeners.

How to Parse the following json response in Android?

The problem with the following JSON response parsing is that is giving the error as "Unterminated object at character 32".
{
"0": {
"review": {
"reviewTime": "2015-09-24 22:07:03",
"author": "John Doe",
"rating_5": 1.5,
"rating": 2
}
},
"1": {
"review": {
"reviewTime": "2015-09-25 18:05:14",
"author": "Samantha",
"rating_5": 5,
"timestamp": 1443184514,
"rating": 5
}
},
"count": 3,
"review_url": "https://localhost/reviews"
}
I'm validated your json using in http://jsonformatter.curiousconcept.com/ and it's valid.
The 32 character is a date and must be quoted. Check in debug mode if the date is quoted.
In one of your comments to your question you wrote that your response looks like:
{ count=2041.0, 4={review={reviewTime=2015-09-24 22:07:03, author=Neha Primith, rating_5=1.5, rating=2.0, reviewTimeFriendly=yesterday}}, 1={review={reviewTime=2015-09-24 22:07:03, author= John Doe, rating_5=1.5, rating=2.0,}}, 0={review={reviewTime=2015-09-25 18:05:14, author=Samantha, rating_5=5.0, rating=5.0}}, , review_url=https://localhost/reviews,count=2 }
But it's not json format. Json format is sensitive to quotes. So make sure you get a properly formatted response

What format is this data stored as? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'd like to parse the following information and would like to identify the format that it is in?
{
"interval": {
"id": 0,
"starts_at": 1317851120683,
"ends_at": 1317851374436
},
"identifier": "2021902",
"category": "music",
"original_category": "",
"buy_link": "http://click.linksynergy.com/fs-bin/stat?id=6z5Z0DsswBo&offerid=162397&type=3&subid=0&tmpid=3664&RD_PARM1=http%253A%252F%252Fitunes.apple.com%252Fca%252Falbum%252Foh-my-what-a-fine-day%252Fid360945836%253Fi%253D360945883%2526uo%253D4%2526partnerId%253D30",
"title": "Oh My, What A Fine Day",
"artist": "Behind Sapphire",
"album": "Behind Sapphire",
"publisher": "Behind Sapphire",
"itunes_song_id": "360945883",
"album_art": {
"src": "http://www.streamon.fm/player/getAlbumArt.php?u=http://a4.mzstatic.com/us/r30/Music/fc/73/1d/mzi.briyobdw.170x170-75.jpg",
"width": 170,
"height": 170,
"alt": "Behind Sapphire",
"link": ""
},
"next_song": "",
"next_buy_link": "",
"next_album_art": {
"src": "",
"width": 0,
"height": 0,
"alt": "",
"link": ""
},
"banner": {
"src": "",
"width": 0,
"height": 0,
"alt": "",
"link": ""
}
}
JSON.
See this: http://developer.android.com/reference/org/json/package-summary.html
JSON, or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange.
You can refer to wikipedia, and you could get some useful information
JSON. In this web http://www.json.org/ you can found a extensive index of libs for parse this information.

Categories

Resources