JSON Reading Object Values - java

I have a JSON response from Spotify that I'm trying to read from. And in my java code I am getting the 'name' value for the album object, and not for the tracked object. Here is the response: https://pastebin.com/fcvTzJJv
Towards the bottom of the JSON Response, there is a name field that says "Money in the Grave", that is what I want to get from the JSON, instead of "The Best in the world pack" which is under the name of the album.
Here is the code that reads this response:
try
{
JSONObject obj = new JSONObject(result);
JSONObject tracks = obj.getJSONObject("tracks");
JSONArray items = tracks.getJSONArray("items");
for(int i = 0; i < items.length(); i++)
{
//album object
JSONObject album = items.getJSONObject(i).getJSONObject("album");
//SHOULD be getting the images array but does not
//artist array
JSONArray artists = album.getJSONArray("artists");
//gets the necessary artist information
for(int j = 0; j < artists.length(); j++)
{
JSONObject artist = artists.getJSONObject(j);
songLists.add(artist.getString("name") + " - " +album.getString("name"));
}
}
}
With the above code, I'm getting "The Best in the World Pack", and not "Money in the Grave". Could someone help explain how to get the track's name, and not the albums name. Thanks

for(int i = 0; i < items.length(); i++)
{
JSONObject values = items.getJSONObject(i);
String name= values.getString("name");
System.out.println(name+" nameee");
//artist array
JSONArray artists = album.getJSONArray("artists");
}
this will work for you and will return "Money In The Grave (Drake ft. Rick Ross)"

You can try like this and it will give that track name
String response = yourJSonData;
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("data","data---"+response);
JSONArray jsArrItems = jsonObject.getJSONObject("tracks").getJSONArray("items");
Log.e("data","data---222>>"+jsArrItems.getJSONObject(0).getString("name")+"<<>>"+jsArrItems);
} catch (JSONException e) {
e.printStackTrace();
}
If you have items as JSONArray more than 1 then can use the loop as well

get name like tems.getJSONObject(i).getString("name") in your items loop as name you are looking is in items array object not in artist object.

Related

Comma is causing unwanted string split

I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:
public List getAnswerStringEdit() {
return answer_edit;
}
I save it as so:
editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
Then retrieve it here:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
answerString = answerString.substring(1, answerString.length() - 1).trim();
String[] array = answerString.split(",");
Finally, I access the array as so:
et_answer1_edit.append(array[0]);
My problem is this - Say I add a questions which has a comma in the middle of it, like -
Question 1- "Why is this broke, I don't know?"
Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:
"Why is this broke, I don't know?"
However, instead I am getting in position 0:
Why is this broke - then position 1 as: I don't know
I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.
The retrieved JSON is as follows:
{
"result": "success",
"message": "Answer Has Been Selected",
"answer": {
"answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
}
}
Any help/advice that can help me to understand what is causing this, would be really appreciated.
Dont split the string using ',' use this
JSONObject jsonObject = new JSONObject(answerString );
JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
String QuestionString1 = jsonArray.get(0).toString();
String QuestionString2 = jsonArray.get(1).toString();
try this one
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject answer= jsonObject.getJSONObject("answer");
JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArrayAnswerEdit);
for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
String que= jsonArrayAnswerEdit.getString(i);
Log.e("json", i + "=" + que);
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject data = jsonObject.getJSONObject("answer");
JSONArray jsonArray = data.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArray);
for (int i = 0; i < jsonArray.length(); i++)
{
String value = jsonArray.getString(i);
String[] parts = value.split(Pattern.quote(","));
for (int j=0; j<parts.length; j++)
{
Log.e("Answer String ", "=" + parts[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
E/=>: ["Why is this broke, I don't know?","What is your favorite song, because I want to know"]
E/Answer String: =Why is this broke
E/Answer String: = I don't know?
E/Answer String: =What is your favorite song
E/Answer String: = because I want to know
After reading all the suggest answers, figured out a simple solution:
First I stored my answers sent from my external database as so -
final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
Then saved in shared pref -
editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
Next to read the answer back out:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
Finally, I could set my Edittext with data from the array:
et_answer1_edit.append(array[0].trim());
et_answer2_edit.append(array[1].trim());

How to get multiple specific values from a key in a JSON Object

So right now I am trying to get information from the logged in user through Facebook graph api.
{"id":"10202628284866677","name":"Rohit Tigga","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/10202628284866677\/","picture":{"data":{"is_silhouette":false,"url":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-xta1\/v\/t1.0-1\/p200x200\/10438582_10202555461926149_8285465463541146116_n.jpg?oh=283ec503c6eb051aad077366155c621d&oe=55E6E24B&__gda__=1445616180_3110e5bf89e9f3050fe623b86d47618b"}},"friends":{"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}}
I was able to get the id, name, profile_pic_url
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
//Here's what you got
Log.e("JSON:", object.toString());
//Find out how to store all user friends efficiently
try {
user_id=object.getString("id");
name=object.getString("name");
profile=object.getString("link");
profile_pic_url = object.getString("picture");
friends = object.getString("friends");
JSONObject pic_object1= (JSONObject) new JSONTokener(profile_pic_url).nextValue();
JSONObject pic_object2 = pic_object1.getJSONObject("data");
profile_pic_url = (String) pic_object2.get("url");
I am more specifically trying to get the ID of each facebook friend from the logged in user. It is from this portion which I have as a string now.
{"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}
I am trying to iterate through the JSON Object and store every id in an array.
But I have been unsuccessful in my attempts.
I am looking at this, yet no luck :/
How to iterate over a JSONObject?
How can I iterate JSONObject to get individual items
How should I go about doing this?
Your goal is to retrieve the ids from the following json string:
{"data":[{"name":"Arthur Shir","id":"10153237510764181"},{"name":"Kanye East","id":"1454465268197338"}],"paging":{"next":"https:\/\/graph.facebook.com\/v2.3\/10202628284866677\/friends?access_token=CAAWKvUHZCc2sBAHDCZCfL1dHLcrrMoqNxHJSXun5vm1iJQlMxaF43ZCTvIj4Oo4sHeRstTEACDpDz45wLj9FwXBXkoqxPyBQvjcQKY4ZCPgEqhcPdyPb3JepOA1KCADTt2ZBIO8NRX8QKdrlvSWxxgEfSH6SY94nUsLZBRslP8OjJ9r9DYm6kih8GwJ7la0w30KbZAi3AFNOUx1FDU9Y38S&limit=25&offset=25&__after_id=enc_AdB7OPjfCizP7TWz68NToMvADpaegj9bV3w8g22S1dgcGTiHSRUC2xQr2uhJDdQczRtmkKPQS9fzh0Fq7LgWLZAsu"},"summary":{"total_count":1289}}
In that case, you can try the following code:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray friends = jsonObject.getJSONArray("data");
for (int index=0; index<friends.length(); ++index){
JSONObject currentFriend = friends.getJSONObject(index);
String id = currentFriend.getString("id");
}
You should be able to grab the JSONArray "data" from the JSON like this
JSONArray array = object.getJSONArray("data");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String id = object.get("id");
//and so on
}

android error when trying to put json data in viewlist php+json+java

I am trying to make a search page for my andriod app using PHP,JSON and SQL.
here is the code that is giving me the error :
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
tempID += json_data.getString("ID") + "\n";
tempID += json_data.getString("heading") + "\n";
tempID += json_data.getString("rank") + "\n:";
}
arr = tempID.split(":");
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
}catch (Exception e){
String errMsg = "error when putting the json data in the list";
Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
}
i have already used this code on another page and it works perfectly but when using it another page/activity it gives me an error when trying to put the json data in listview.
i would guess the problem is when i am setting the ArrayAdapter, have i done anything wrong?
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
To answer your final question:
//array list
List<String> your_array_list = new ArrayList<String>();
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
your_array_list.add(json_data.getString("ID") + "\n");
your_array_list.add(json_data.getString("heading") + "\n");
your_array_list.add(json_data.getString("rank") + "\n:");
}
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,your_array_list));
//then, to get the items from inside the adapter:
for(String item_in_list : your_array_list){
System.out.println(item_in_list);
}
To answer the original question:
Check out http://jsonformatter.curiousconcept.com/ for formatting issues
Try looking at this info:
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
FYI: The inbuilt JSONObject and JSONArray cannot be used to get certain json responses.
You could try downloading a small library named "json-simple-1.1.1.jar" from this link https://json-simple.googlecode.com/files/json-simple-1.1.1.jar.

How can parse my json result

I am working in android. I want to parse my json data.
This is my json data:-
{
"response":{
"groups":[
{
"type":"nearby",
"name":"Nearby",
"items":[
{
"id":"4ed0c8f48231b9ef88fe5f09",
"name":"Banayan Tree School",
"contact":{
},
"location":{
"lat":26.857954980225713,
"lng":75.76602927296061,
"distance":510
},
"categories":[
{
"id":"4bf58dd8d48988d1a8941735",
"name":"General College & University",
"pluralName":"General Colleges & Universities",
"shortName":"Other - Education",
"icon":"https:\/\/foursquare.com\/img\/categories\/education\/default.png",
"parents":[
"Colleges & Universities"
],
"primary":true
}
],
"verified":false,
"stats":{
"checkinsCount":5,
"usersCount":4,
"tipCount":0
},
"hereNow":{
"count":0
}
}
]
}
]
}
}
i want to use icon to show icon in imageview. please suggest me how can i get this icon value and how can i user this icon url in imageview.
Thank you in advance.
i am trying this, but still it is creating error:-
this is my code:- but still is creating error:-
JSONArray groups= (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length= groups.length(); if (length > 0){ for (int i = 0; i < length; i++)
{
JSONObject group= (JSONObject) groups.get(i); JSONArray items =(JSONArray) group.getJSONArray("items");
for (int j = 0; j < items.length(); j++)
{
JSONObject item = (JSONObject) items.get(j);
JSONObject iconobject=(JSONObject) item.getJSONObject("categories");//this is creating error that JSON.typeMismatch
venue.icon=iconobject.getString("icon");
}}}}
The class JSONObject can help you:
String data = ... // your json data
JSONObject json = new JSONObject(data);
You can access nodes in your structure with help of getJSONObject(String) and getJSONArray(String).
For example:
JSONObject response = json.getJSONObject("response");
JSONArray groups = response.getJSONArray("groups");
JSONObject firstGroup = groups.getJSONObject(0);
// and so on
When you got your node that contains your icon value you can use the getString(String) method to get the icon url:
JSONObject firstCategory = categories.getJSONObject(0);
String iconUrl = firstCategory.getString("icon");
After you got the url you have to download the image before you can use it. How to download an image from an url is described here
When you downloaded the image you can update the imageview:
Bitmap image = loadBitmap(iconUrl); // how to implement loadBitmap is shown in the link above
ImageView iv = findViewById(R.id.my_imageview);
iv.setImageBitamp(image);
Try this:
try {
JSONArray jArray = new JSONArray(result);
// get into the 'groups' array
JSONObject jData = jArray.getJSONObject(0);
JSONArray jGroupsArray = jData.getJSONArray("groups");
// get into the 'items' array
jData = jArray.getJSONObject(2);
JSONArray jItemsArray = jData.getJSONArray("items");
// get into the 'categories' array
jData = jArray.getJSONObject(4);
JSONArray jCategoriesArray = jData.getJSONArray("categories");
// get into the 'icon' value as String and use it as you please
jData = jArray.getJSONObject(4);
String iconURL = jData.getString("icon");
} catch (JSONException e) {
Log.e(Constants.LOG_TAG, "Error parsing data", e);
}
Hope this helps
Refer to the JSON documentation: http://www.json.org/javadoc/org/json/package-summary.html. It's really simple.
In your case, you would have to read the JSON string to a JSON object, then parse "response" as a JSONObject, "groups" as a JSONArray inside "response", iterate through the JSONObjects contained in the "groups" array, parse "Items" as a JSONArray inside your JSONObject, and son on...
You should be able to get to the URL in no time.

json in java getting the correct values from a list

I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}

Categories