I want to fetch array from json object but get error
When I do jarray2 = object1.getJSONArray(route);
I get the following error
APPÂ CRASH: No value for (the following JSON)
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.42252295423907,
"lng": 4.873809814453125
},
"name": "Coenplein, A10, Amsterdam, Noord, Amsterdam, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1035RN, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.28674750920209,
"lng": 4.941873550415039
},
"name": "Holendrechterzijweg, Ouderkerk aan de Amstel, Ouder-Amstel, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1191LJ, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.0727536539532,
"lng": 4.32861328125
},
"name": "87, Zwetstraat, Rivierenbuurt, The Hague, MRDH, South Holland, Netherlands, 2515VE, The Netherlands",
"_initHooksCalled": true
}]
Here is the code
try
{
object1 = new JSONObject(response);
jarray1 = object1.getJSONArray("selected_route_data");
for(int i=0;i<jarray1.length();i++)
{
json1 = jarray1.getJSONObject(i);
String route_id = json1.getString("route_id").toString();
String route_name = json1.getString("route_name").toString();
String route = json1.getString("route_data").toString();
jarray2 = object1.getJSONArray(route);
}
}
catch (JSONException e)
{
Log.e("APP CRASH", e.getMessage());
}
It appears the JSON you are attempting to parse does not contain the values you are looking for. None of the elements in the array contain either route_id, route_name or route_data.
You should check if an element exists in the JSON you are parsing, you can do something like
String route_id = null;
if (!json1.optString("route_id").isEmpty()) {
route_id = json1.getString("route_id").toString();
}
Related
I have a nested JSON array which I want to decode. I have already found a way to decode a specified info in the object but it's not working so good.
This is the code I used to decode (name, cover and street) from the JSON object:
JSONArray jsonArray = response.getJSONArray("data");
for (int i=0; i < jsonArray.length();i++){
JSONObject events = jsonArray.getJSONObject(i);
String name = events.getString("name");
JSONObject cover = events.getJSONObject("cover");
String imgurl = cover.getString("source");
JSONObject place = events.getJSONObject("place");
JSONObject loc = place.getJSONObject("location");
String street = loc.getString("street");
ItemListView item = new ItemListView(name,street,imgurl);
listItems.add(item);
adapter = new ItemListAdapter(listItems, getActivity());
recyclerView.setAdapter(adapter);
}
I want to decode more info like description, end_time and start_time.
The JSON data structure looks like this:
{
"data": [
{
"description": "",
"end_time": "",
"name": "",
"place": {
"name": "",
"location": {
"city": "",
"country": "",
"latitude": 0000000,
"longitude": 000000,
"street": ""
},
"id": ""
},
"start_time": "",
"id": ""
},
{
"description": "",
"end_time": "",
"name": "",
"place": {
"name": "",
"location": {
"city": "",
"country": "",
"latitude": 0000000,
"longitude": 000000,
"street": ""
},
"id": ""
},
"start_time": "",
"id": ""
}
]
}
I put the decoded info in a ListView in my Android app and that is why I have an adapter and ListView in the code.
Any help is greatly appreciated :)
Thanks in advance.
This is simple you can get other string like this -:
JSONArray jsonArray = response.getJSONArray("data");
for (int i=0; i < jsonArray.length();i++){
JSONObject events = jsonArray.getJSONObject(i);
String description= events.getString("description");
String end_time= events.getString("end_time");
String start_time= events.getString("start_time");
}
I have to parse the Json below. I know how to obtain Json from a JsonArray when it has a key. How do I do this when I don't have any key?
[
{
"kind": "track",
"id": 253792869,
"created_at": "2016/03/21 15:20:47 +0000",
"user_id": 167064157,
"duration": 9457,
"commentable": true,
"state": "finished",
"original_content_size": 375488,
"last_modified": "2016/03/21 15:20:48 +0000",
"sharing": "public",
"tag_list": "commercial",
"permalink": "2016-03-08_lbs_bigfm_spot_3",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "",
"title": "2016-03-08_LBS_BigFM_SPOT_3",
"description": "",
"label_name": null,
"release": null,
"track_type": null,
"key_signature": null,
"isrc": null,
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/253792869",
"user": {
"id": 167064157,
"kind": "user",
"permalink": "user690075536",
"username": "user690075536",
"last_modified": "2016/02/26 08:19:23 +0000",
"uri": "https://api.soundcloud.com/users/167064157",
"permalink_url": "http://soundcloud.com/user690075536",
"avatar_url": "https://i1.sndcdn.com/avatars-000159639971-j1awdb-large.jpg"
},
"permalink_url": "http://soundcloud.com/user690075536/2016-03-08_lbs_bigfm_spot_3",
"artwork_url": "https://i1.sndcdn.com/artworks-000152760877-s9mcat-large.jpg",
"waveform_url": "https://w1.sndcdn.com/8Ijd5YlUn9iW_m.png",
"stream_url": "https://api.soundcloud.com/tracks/253792869/stream",
"playback_count": 0,
"download_count": 0,
"favoritings_count": 0,
"comment_count": 0,
"attachments_uri": "https://api.soundcloud.com/tracks/253792869/attachments"
}
]
Valid JSON:
{
"abc":[
{
"name":"Ram"
},
{
"name":"Shyam"
},
{
"name":"Mohan"
},
{
"name":"Pankaj"
},
{
"name":"Komal"
}
]
}
try
{
JSONArray jsonArray = new JSONArray(jsonStrFromSoundCloud);
for (int i = 0; i < jsonArray.length(); i++) {
//loop in array
}
} catch (JSONException e) {
e.printStackTrace();
}
I got my answer, I bind this array inside a json object. then fetch it.
similar like this.
"{\"data\":"+ jsonArray+"}";
I tried to solve similar issue by creating a json array.
[{ "name":"dave",
"age":23
},
{
"name" : "dexter"
"age" : 24
}]
Here is my POJO
public class MyPojo {
private String name;
private int age;
// Getter & Setters
}
And this is all you need to do to parse the JSON to List object.
Type listType = new TypeToken<ArrayList<MyPojo>>(){}.getType();
List<MyPojo> jsonObject = new Gson().fromJson(response, listType);
Hope this helps. :)
EDIT
Don't forget to Import : import java.lang.reflect.Type;
I have a json string as shown below
{
"college": {
"id": "RPD4007",
"address": "#302, 1 st cross"
},
"deparment": {
"department1": {
"name": {
"maths": {
"chapter": 1,
"name": "algebra",
"module_id": "01"
},
"electronics": {
"chapter": 1,
"name": "ec",
"module_id": "01"
}
}
},
"department2": {
"name": {
"english": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
},
"electrical": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
}
}
}
}
}
I have tried to convert this json sring to json object ,
string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object
JSONObject object = jobj.getJSONObject("college");
But the jobj output I got is in reverse order of json string .Like below,
{
"college": {
"id": "RPD4007",
"address": "#302, 1 st cross"
},
"deparment": {
"department2": {
"name": {
"electrical": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
},
"english": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
}
}
},
"department1": {
"name": {
"electronics": {
"chapter": 1,
"name": "ec",
"module_id": "01"
},
"maths": {
"chapter": 1,
"name": "algebra",
"module_id": "01"
}
}
}
}
}
How to get it in same order as it is?
I think you are making jsonObject for two times.
Just do something like this
you have String that contains JSON DATA
Make an object for that which you did
string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object
then make a loop to get the object inside that object using
String college = jobj.getString("college");
The answers here: JSON order mixed up
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
I am trying to access value of 'cod' from the json string :
{"coord":{"lon":73.86,"lat":18.52},"sys":{"message":0.0293,"country":"IN","sunrise":1428972502,"sunset":1429017681},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":304.301,"temp_min":304.301,"temp_max":304.301,"pressure":951.61,"sea_level":1021.56,"grnd_level":951.61,"humidity":36},"wind":{"speed":2.06,"deg":302.501},
"clouds":{"all":24},"dt":1428996633,"id":1259229,"name":"Pune","cod":200}
But I am not able to get this value from my code. the code I am using to access this value from json string is as:
try{
JSONObject jsObject=(new JSONObject(JsonString)).getJSONObject("coord");
if( jsObject.getInt("cod")==200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
In the if condition, you are trying to access the key "cod" in the array {"lon":73.86,"lat":18.52}. It will throw a JSONException.
Try this :
try{
JSONObject jsonmain = new JSONOBject(JsonString);
if(jsonmain.getInt("cod") == 200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
Your json is:
{
"coord": {
"lon": 73.86,
"lat": 18.52
},
"sys": {
"message": 0.0293,
"country": "IN",
"sunrise": 1428972502,
"sunset": 1429017681
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 304.301,
"temp_min": 304.301,
"temp_max": 304.301,
"pressure": 951.61,
"sea_level": 1021.56,
"grnd_level": 951.61,
"humidity": 36
},
"wind": {
"speed": 2.06,
"deg": 302.501
},
"clouds": {
"all": 24
},
"dt": 1428996633,
"id": 1259229,
"name": "Pune",
"cod": 200
}
The key "cod" is not nested inside "coord".
Try:
new JSONObject(JsonString)).getInt("cod");
Actually you are trying wrong JSON Object.
String cod=(new JSONObject(JsonString)).getJSONObject("code").toString();
//you may need to try catch block
if( Integer.parseint(cod)==200) {
.... Your logic
}
I am working on app in which I have to parse below JSON.
Anyone can anyone tell me how to do this?
{
"navigation_entries": {
"home": {
"children": [
"favorites",
"calendar",
"offers",
"wineries",
"dining",
"lodging",
"things_to_do",
"weather",
"settings"
],
"banner_image": "home_page_banner",
"icon": {
"small": "icon_home_small",
"large": "icon_home_large"
},
"type": "home_page",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Home"
},
"wineries": {
"display_name": "Wineries",
"icon": {
"small": "icon_wineries_small",
"large": "icon_wineries_large"
},
"line_template": "wineries_list_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Wineries",
"type": "leaf_list",
"leaf_template": "wineries_leaf_template",
"section": "wineries"
},
"dining": {
"display_name": "Dining",
"icon": {
"small": "icon_dining_small",
"large": "icon_dining_large"
},
"line_template": "dining_list_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Dining",
"type": "leaf_list",
"leaf_template": "dining_leaf_template",
"section": "dining"
},
"offers_dining": {
"display_name": "Offers => Dining",
"list_name": "Dining",
"line_template": "offers_dining_list_template",
"type": "leaf_list",
"leaf_template": "offers_dining_leaf_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"section": "offers_dining"
},
"favorites": {
"display_name": "Favorites",
"icon": {
"small": "icon_favorites_small",
"large": "icon_favorites_large"
},
"type": "favorites",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Favorites"
},
"offers": {
"display_name": "Offers",
"children": [
"offers_wineries",
"offers_dining",
"offers_lodging",
"offers_things_to_do"
],
"icon": {
"small": "icon_offers_small",
"large": "icon_offers_large"
},
"type": "navigation_list",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Offers"
}
},
"type": "navigation"
}
You can use this website to format your JSON string in a in an easier way to view it.
Android provides an appropiate library to do what you want.
This is the manual page you need to comprehend how to use Android JSON API.
And here you can see a tutorial to understand how to parse JSON string.
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
If the example above is your string, you can parse it passing it to the JSONObject constructor:
String jsonString = "...."; // the above string
try {
JSONObject obj = new JSONObject(jsonString);
} catch (JSONException e) {
// This exception is thrown if jsonString is not correctly formatted
}
Now, if you want to get the JSONObject labled "GlossList", inside the string above, you can do this:
JSONObject glossList = obj.getJSONObject("glossary").getJSONObject("GlossDiv").getJSONObject("GlossList");
There is also another possibility: you can also obtain some JSONArray. In our example, the array GlossSeeAlso:
JSONArray glossSee = glossList.getJSONObject("GlossEntry").getJSONObject("GlossDef").getJSONArray("GlossSeeAlso");
To get directly a value of this array, you can use the method getString(int i); if the contend of the array is a JSONObject, you can use the method getJSONObject(int i). You can also use the method getString(String lable) to get directly a string in a JSONObject:
String title = glossDive.getString("title");
String firstElement = glossSee.getString(0);
Other examples are available in the official JSON site.
You can use JSONObject and JSONTokener like this:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
jsonlint.com has a very good json formatter. this should make your text easily understandable.
for parsing this data, you can use JSONObject (org.json.JSONObject)