Parsing JSON response from Volley - android

This might be a simple question, so sorry for that. I'm trying to develop a radio app for my internet radio station. I'm using JSON format for the requests (Example JSON) to get information from my station. For example the "title" tag. I want to get this information.
My first try:
JSONObject data = response.getJSONObject("data");
songname.setText(data.getString("title"));
But the problem is that I cannot get this information. What can I do? Thanks in advance.

As your JSON do like this
JSONObject josnOBJ = new JSONObject(response);
JSONArray jArray = josnOBJ.getJSONArray("data");
JSONObject jsonData = null;
String title = null;
for (int i=0; i < jArray.length(); i++)
{
try {
jsonData = jArray.getJSONObject(i);
title= jsonData .optString("title");
} catch (JSONException e) {
// Oops
}
}
songname.setText(title);

You could use some generic JSON parsers instead of manual work. Eg: https://github.com/bajicdusko/AndroidJsonProvider
Just create model class regarding your json content. Check examples in README on github url.
Hope i could help.

You can use GSON library in case you have lot of values to fetch from JSON ,that would take care of everything for you.

Related

Why I can't read json

I'm trying to read JSON but I got below error.
2019-08-27 13:12:43.352 27379-27379/com.test W/System.err: org.json.JSONException: Value transcript of type java.lang.String cannot be converted to JSONObject
JSON
{"transcript":{"text":[{"content":"Flood!","dur":"1.76","start":"2.28"},{"content":"Listen up, there’s a flood coming!","dur":"2.24","start":"4.52"},{"content":"Oy lads, flood!","dur":"1.92","start":"7.88"},{"content":"There’s a flood –","dur":"1.24","start":"10.72"},{"content":"Maurice, they’re not listening.","dur":"1.84","start":"13.96"},{"content":"We’ve got to give them\na good old-fashioned fish slappin’.","dur":"2.8","start":"15.96"},{"content":"Fish Slap!","dur":"1.04","start":"20.52"},{"content":"Fish Slap!","dur":"1","start":"22.32"},{"content":"Fish Slap!","dur":"1.2","start":"24.12"},{"content":"Double Fish Slap!","dur":"1.24","start":"25.84"},{"content":"See, guys? Flood’s here.","dur":"1.56","start":"27.84"},{"content":"Tub Rider!","dur":"2.48","start":"31.56"},{"content":"SEASON 1\nTHE FLOOD","dur":"1","start":"35.32"},{"content":"Because I’m in a tub!","dur":"1.04","start":"36.48"},{"content":"PREPARE TO BATTLE ON A BOAT","dur":"1.48","start":"37.68"}]}}
Code
try {
JSONObject jsonObject = new JSONObject("transcript");
JSONArray jsonArray = new JSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
Put your json into a String and then try to parse it :
String json = "{\"transcript\":{\"text\":[{\"con ...}";
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject = new JSONObject("transcript");
JSONArray jsonArray = new JSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
Remember to escape your double quotes with backslash
From your question and code you've provided, I understand that you are new and unfamiliar with the JSON APIs in Android. For this, I suggest you read the official documentation and get yourself familiar with org.json API (JSONObject, JSONArray):
https://developer.android.com/reference/org/json/JSONObject
https://developer.android.com/reference/org/json/JSONArray
After, you may want to practice and follow some tutorials on serialization/deserialization of JSON in Android using the org.json API. Here is a fairly complete tutorial I just found for you on the net (just an example, there are literally hundreds out there):
https://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html
String response = "{"transcript":{"text":[{"content":"Flood!","dur":"1.76","start":"2.28"},{"content":"Listen up, there’s a flood coming!","dur":"2.24","start":"4.52"},{"content":"Oy lads, flood!","dur":"1.92","start":"7.88"},{"content":"There’s a flood –","dur":"1.24","start":"10.72"},{"content":"Maurice, they’re not listening.","dur":"1.84","start":"13.96"},{"content":"We’ve got to give them\na good old-fashioned fish slappin’.","dur":"2.8","start":"15.96"},{"content":"Fish Slap!","dur":"1.04","start":"20.52"},{"content":"Fish Slap!","dur":"1","start":"22.32"},{"content":"Fish Slap!","dur":"1.2","start":"24.12"},{"content":"Double Fish Slap!","dur":"1.24","start":"25.84"},{"content":"See, guys? Flood’s here.","dur":"1.56","start":"27.84"},{"content":"Tub Rider!","dur":"2.48","start":"31.56"},{"content":"SEASON 1\nTHE FLOOD","dur":"1","start":"35.32"},{"content":"Because I’m in a tub!","dur":"1.04","start":"36.48"},{"content":"PREPARE TO BATTLE ON A BOAT","dur":"1.48","start":"37.68"}]}}"
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject transcript = jsonObject.getJSONObject("transcript")
JSONArray jsonArray = transcript.getJSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
You need to pass json string to Json object first.
please refer the below code, it might work for you.
try {
JSONObject obj = new JSONObject("{\"transcript\":{\"text\":[{\"content\":\"Flood!\",\"dur\":\"1.76\",\"start\":\"2.28\"},{\"content\":\"Listen up, there�s a flood coming!\",\"dur\":\"2.24\",\"start\":\"4.52\"},{\"content\":\"Oy lads, flood!\",\"dur\":\"1.92\",\"start\":\"7.88\"},{\"content\":\"There�s a flood �\",\"dur\":\"1.24\",\"start\":\"10.72\"},{\"content\":\"Maurice, they�re not listening.\",\"dur\":\"1.84\",\"start\":\"13.96\"},{\"content\":\"We�ve got to give them\\na good old-fashioned fish slappin�.\",\"dur\":\"2.8\",\"start\":\"15.96\"},{\"content\":\"Fish Slap!\",\"dur\":\"1.04\",\"start\":\"20.52\"},{\"content\":\"Fish Slap!\",\"dur\":\"1\",\"start\":\"22.32\"},{\"content\":\"Fish Slap!\",\"dur\":\"1.2\",\"start\":\"24.12\"},{\"content\":\"Double Fish Slap!\",\"dur\":\"1.24\",\"start\":\"25.84\"},{\"content\":\"See, guys? Flood�s here.\",\"dur\":\"1.56\",\"start\":\"27.84\"},{\"content\":\"Tub Rider!\",\"dur\":\"2.48\",\"start\":\"31.56\"},{\"content\":\"SEASON 1\\nTHE FLOOD\",\"dur\":\"1\",\"start\":\"35.32\"},{\"content\":\"Because I�m in a tub!\",\"dur\":\"1.04\",\"start\":\"36.48\"},{\"content\":\"PREPARE TO BATTLE ON A BOAT\",\"dur\":\"1.48\",\"start\":\"37.68\"}]}}");
JSONObject transcriptObject = obj.getJSONObject("transcript");
Log.d("transcript object",transcriptObject.toString());
JSONArray textArray = transcriptObject.getJSONArray("text");
Log.d("text array",textArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
You can use GSON library for json parsing.
Instead of String.valueOf(jsonArray.getJSONObject(0).get("content"))
you could use :
jsonArray.getJSONObject(0).getString("content")

Android Multiple Level JsonObject and JsonArray Parsing with Model class

{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Parsing json response from google direction api

I'm trying to parse the JSON response from google direction api in my android program. This is the request link bellow. I'm skipping the JSON response here because its too long and simply clicking on the link will show it.
http://maps.googleapis.com/maps/api/directions/json?origin=Windsor&destination=Leamington&sensor=false&avoid=highways&mode=walking
My code for parsing the response :
try {
JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
this.responseString = responseObject.getString("status") ;
JSONArray routesArray = responseObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs ;
JSONObject leg ;
JSONArray steps ;
JSONObject dist;
Integer distance ;
if(route.has("legs")) {
legs = route.getJSONArray("legs");
leg = legs.getJSONObject(0) ;
steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
JSONObject step = steps.getJSONObject(i);
if(step.has("distance")) {
dist = (JSONObject) step.get("distance");// throws exception
//I would like to take the distance value and do something with it
//if(dist.has("value"))
// distance = (Integer) dist.get("value") ;
}
}
}
else
this.responseString = "not found" ;
} catch ( Exception e) {
e.printStackTrace() ;
}
This throws an exception (again skipping because the JSON response is too big. The stack trace shows the entire response string) :
org.json.JSONException: Expected ':' after polyline at character 13837 of {
"routes" : [
{
"bounds" : {
"northeast" : { ....
I have tried using the getJSONObject function instead of get, but I get the same exception.
dist = step.getJSONObject("distance");
Can anyone please help me by pointing out what am I missing here ? I'm not very familiar with parsin JSON on android yet, so it's quite likely that I'm making a silly mistake somewhere. Thanks.
Another similar post on this site, but not quite the same : JSON parsing of Google Maps API in Android App
As you aren't so familiar, i'd suggest parsing JSON using Gson, esp for complex responses. The case would suit better in your case.
I have used Gson for parsing responses from Google Maps API, Places API and more...
You may be better off using Gson to parse, map data and your model classes. Eg.:
Gson gson = new Gson();
ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like
#SerializedName. (So no need to use Serializable)
You can use a for-each loop and verify or operate the data from the model classes.
for(Modelclass object: modelClass.getList()) {
}
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
Also, use a for-each instead of for(;;) where ever possible.
Check these:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json
I am working on the same API right now, thought this would also help, for the model classes:
Displaying multiple routes using Directions API in Android
Try this..
steps = leg.getJSONArray("steps");
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
if(steps.has("distance")) {
JSONObject new_onj = steps.getJSONObject(i);
dist = new_onj.getJSONObject("distance");
if(dist.has("value"))
distance = (Integer) dist.get("value");
}
}
Your for loop never sets a value for step - are you missing a line
step = steps.getJSONObject(i);
at the top of your for loop?

Retrieve value from JSON responce

I am writing an android application and currently i am getting a JSON reply:
{"Error":"User already exists"}
this is an example of the messages that i get returned
the part that i am after is : "User already exists" and i need to parse it.
The message is currently stored in a string so i would need to convert this to a JSONArray to then convert it to a JSONOject to then be able to call the getString().
what would be the best way to do this?
this may Helps You
String Respones= "{\"Error\":\"User already exists\"}";
try {
JSONObject jobj = new JSONObject(Respones);
String strError = jobj.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can do it directly with JSONTokener and JSONObject if you want ot use default andoid tools.
If you want better, look into the Jackson lib, it's very powerful, open source, kind of standard:
Android JSON Jackson Tutorial
Try this code
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String result = jsonObject.getString("Error").toString().trim();
}

How to read JSON parent tags in Android

I need your help with following matter. I want to read the parent tags of a JSON file. Below is my JSON file content;
{
"ebook":
[
{"id":"1","name":"book1"},
{"id":"2","name":"book2"}
],
"ebrochure":
[
{"id":"1","name":"brochure1"},
{"id":"2","name":"brochure2"}
],
"emenu":
[
{"id":"1","name":"menu1"},
{"id":"2","name":"menu2"}
]
}
I just need to find out how many parents tags in the JSON and what are they. According to my given JSON file the answers should be 3 (there are 3 parent JSON tags) and "ebooks, ebrochure, emenu" (names of the parent tags). Is ther any JAVA class I can get my work done?
I know how to read a full JSON file. First we pass the JSON to a JSONObject and then pass children to a JSONArray by using getJSONArray() method.
But getJSONArray() method needs the name of the parent tag. According to my example it can be ebook, ebrochure or emenu. Assume there is a circumstance where we can't see the content of the JSON only access the URL. In such a situation I need to find out how many parents tags are there and what are the names of them.
That's my problem. Thanks in advance for helping me :-)
You should read the documentation for JSONObject.names
Basically, names()(in Android) can be used to get an array of field names, and then use those as your keys. I won't do a full example here because you'll learn better if you try for yourself.
public static String Fechingdata(String response){
Id1.clear();
Id2.clear();
Id3.clear();
name1.clear();
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForResponse1(jsonobject.getString("ebook"),1);
parseForResponse2(jsonobject.getString("ebrochure"),2);
parseForResponse3(jsonobject.getString("emenu"),3);
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
private static void parseForResponse1(String res,int i) {
try{
JSONArray jsonarray1 = new JSONArray(res);
Log.d("jsarry1",""+jsonarray1.length());
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
if(i ==1){
Id1.add(jsonobject.getString("id"));
name1.add(jsonobject.getString("id"));
}
if(i ==2){
Id2.add(jsonobject.getString("id"));
name2.add(jsonobject.getString("id"));
}
if(i ==2){
Id3.add(jsonobject.getString("id"));
name3.add(jsonobject.getString("id"));
}
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
This try this json parsging
JSONObject jobj = new JSONObject(Your Json String);
JSONArray jarray=jobj.names();
for(int i=0;i<jarray.length();i++){
Log.e("parenttag",jarray.getString(i));
}
by this u will get all parent tag u have in your jsonString

Categories

Resources