How to access value from json issue in android - android

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
}

Related

Convert json string to json object without changing the keys order

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.

how to parse json in android which contains object inside object and populate in listview

{
"data": [
{
"0": {
"degree": "HSC",
"start_date": "01-01-2007",
"end_date": "01-01-2008"
},
"1": {
"degree": "BE",
"start_date": "01-01-2008",
"end_date": "31-05-2012"
},
"2": {
"degree": "MCM",
"start_date": "29-07-2015",
"end_date": "31-07-2015"
},
"3": {
"exp_designation": "aaa",
"exp_description": "aa",
"exp_startdate": "23-07-2015",
"exp_enddate": "01-07-2015",
"latest": "0"
},
"4": {
"exp_designation": "aaa",
"exp_description": "asasasas",
"exp_startdate": "01-07-2015",
"exp_enddate": "31-07-2015",
"latest": "0"
},
"user_id": "1",
"user fullname": "",
"user_phone": "2147483647",
"user_email": "",
"user_address": "Uruli kanchan",
"user_status": "",
"user_speciality": "eye",
"username": "",
"password": "niki"
}
]
}
How to parse this json in android ? i want to display
"0": {
"degree": "HSC",
"start_date": "01-01-2007",
"end_date": "01-01-2008"
},
"1": {
"degree": "BE",
"start_date": "01-01-2008",
"end_date": "31-05-2012"
},
"2": {
"degree": "MCM",
"start_date": "29-07-2015",
"end_date": "31-07-2015"
},
"3": {
"exp_designation": "aaa",
"exp_description": "aa",
"exp_startdate": "23-07-2015",
"exp_enddate": "01-07-2015",
"latest": "0"
},
"4": {
"exp_designation": "aaa",
"exp_description": "asasasas",
"exp_startdate": "01-07-2015",
"exp_enddate": "31-07-2015",
"latest": "0"
},
these in custom list view ?
is it a correct json ?
how to parse ?
currently im getting some json data as follows,
// Getting JSON Array
user = json.getJSONArray("data");
JSONObject feedObj = user.getJSONObject(0);
item.setUserid(feedObj.getInt("user_id"));
item.setUserFullname(feedObj.getString("user fullname"));
item.setUserPhone(feedObj.getString("user_phone"));
MobileNo.setText(item.getUserPhone());
item.setUserEmail(feedObj.getString("user_email"));
Email.setText(item.getUserEmail());
item.setUserAddress(feedObj.getString("user_address"));
Address.setText(item.getUserAddress());
item.setUserStatus(feedObj.getString("user_status"));
item.setUserSpeciality(feedObj.getString("user_speciality"));
SelSpeciality.setText(item.getUserSpeciality());
item.setUsername(feedObj.getString("username"));
item.setPassword(feedObj.getString("password"));
item.setImgSmall(feedObj.getString("img_small"));
item.setImgLarge(feedObj.getString("img"));
item.setUserConnection(feedObj.getString("connection"));
I think that you should consider using some library like Gson. If using Gson, you can create an a model with the same naming as your Json.
Here is a reference: How can I convert JSON to a HashMap using Gson?

Facebook Profile Information JSON Parsing in Android

For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
{
"id": "1464730016",
"name": "Ravi Tamada",
"first_name": "Ravi",
"last_name": "Tamada",
"link": "https://www.facebook.com/ravi8x",
"username": "ravi8x",
"birthday": "12/22/1988",
"hometown": {
"id": "112158005464147",
"name": "Baruva"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
"work": [
{
"employer": {
"id": "179366562092719",
"name": "ByteAlly"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": "124917314217511",
"name": "Product Head"
}
]
}
],
"favorite_athletes": [
{
"id": "18620649907",
"name": "Virat Kohli"
}
],
"education": [
{
"school": {
"id": "131587206873093",
"name": "Raghu Engineering College (REC)"
},
"degree": {
"id": "140065339390579",
"name": "B.Tech"
},
"year": {
"id": "142963519060927",
"name": "2010"
},
"type": "Graduate School",
"classes": [
{
"id": "192259410803415",
"name": "2010",
"with": [
{
"id": "584960408",
"name": "Santosh Patnaik"
}
],
"from": {
"id": "584960408",
"name": "Santosh Patnaik"
}
}
]
}
],
"gender": "male",
"relationship_status": "Single",
"website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
"timezone": 5.5,
"locale": "en_US",
"languages": [
{
"id": "106059522759137",
"name": "English"
},
{
"id": "107617475934611",
"name": "Telugu"
},
{
"id": "112969428713061",
"name": "Hindi"
},
{
"id": "343306413260",
"name": "Tamil"
}
],
"verified": true,
"updated_time": "2012-03-02T17:04:18+0000"
}
JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
if(data != null)
{
for(int i = 0 ; i < data.length() ; i++)
{
JSONObject c = data.getJSONObject(i);
String type = c.getString("type");
if(type.equalsIgnoreCase("college"))
{
JSONObject school = c.getJSONObject("school");
String id2 = school.getString("id");
String name2 = school.getString("name");
JSONObject year = c.getJSONObject("year");
String id_y = school.getString("id");
String name_y = school.getString("name");
}
}
}
Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");
Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");
// get school name
String schoolName = jsonSchool.getString("name");

skipping null values when parsing json in android?

I am parsing json object from facebook.
In my facebook json object, there are string keys inside key array "data".
My Code as follows,
"data": [
{
"id": "100001211447563_300696056647440",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee is now using Facebook in English (US).",
"story_tags": {
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"type": "status",
"created_time": "2012-01-19T09:13:04+0000",
"updated_time": "2012-01-19T09:13:04+0000",
"comments": {
"count": 0
}
},
{
"id": "100001211447563_298802933503419",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee started using Graph API Explorer.",
"story_tags": {
"23": [
{
"id": 145634995501895,
"name": "Graph API Explorer",
"offset": 23,
"length": 18
}
],
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"picture": "http://photos-a.ak.fbcdn.net/photos-ak-snc1/v43/11/145634995501895/app_1_145634995501895_4870.gif",
"link": "http://developers.facebook.com/tools/explorer/",
"caption": "A tool to help you browse objects within the Facebook Graph API, manage permissions, obtain access tokens and generally learn how it all works.",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/100001211447563/posts/298802933503419"
},
{
"name": "Like",
"link": "http://www.facebook.com/100001211447563/posts/298802933503419"
}
],
"type": "link",
"created_time": "2012-01-16T09:47:57+0000",
"updated_time": "2012-01-16T09:47:57+0000",
"comments": {
"count": 0
}
},
{
"id": "100001211447563_298789650171414",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee likes myFBCovers.com.",
"story_tags": {
"15": [
{
"id": 160901873998019,
"name": "myFBCovers.com",
"offset": 15,
"length": 14
}
],
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"type": "status",
"created_time": "2012-01-16T08:57:33+0000",
"updated_time": "2012-01-16T08:57:33+0000",
"comments": {
"count": 0
}
}
when I parsing this json object, String key "likes" is sometimes exist and sometimes do not exist in "data" jsonArray. So when I parsing JsonString "likes", sometimes I gets JSONException since I am parsing null value. Is there any way to skipping "null" json value?
Please help me regarding this.
if try catch it, next processes will be skipped.
you can check by isNull("name") method.
Edit: this is to check key. since you mentioned key exists sometimes. did you mean the value?
use JSONObjects method has(key)
data = (JSONObject) new JSONTokener(jsonObjRecv.toString()).nextValue();
if data.has("like"){
...
}
to check whether the value is null check with isNull("name")

How do I parse this JSON string?

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)

Categories

Resources