Parse multiple JSON objects in Android - android

i'm confused on how to parse this JSON.
So far this is my approach. Also please tell me the right approach for parsing JSON in Android
JSON:
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
Now the "currently" object is being parsed but when i try to parse "minutely" object it shows no value in Logcat
Here's my code:
JSONObject forecast = new JSONObject(jsonData);
JSONArray summary = new JSONArray(jsonData);
String timezone = forecast.getString("timezone");
String city = getLocationName(forecast.getDouble("latitude"), forecast.getDouble("longitude"));
JSONObject currently = forecast.getJSONObject("currently");
JSONArray hour = summary.getJSONArray("minutely");
for (int i = 0; i < hour.length(); i++) {
JSONObject jsonObject = hour.getJSONObject(i);
String summary = jsonObject.getString("summary");
}
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemp(currently.getDouble("temperature"));
currentWeather.setTimezone(timezone);
currentWeather.setLocation(city);

Based on the response from the endpoint url that you added in comments the parsing would look like this
JSONObject forecast = new JSONObject(jsonData);
double latitude = forecast.getDouble("latitude");
double longitude= forecast.getDouble("longitude");
String timezone = forecast.getString("timezone");
JSONObject jsonObjCurrently= forecast.getJSONObject("currently");
//parse string, long and double objects within jsonObjCurrently accordingly
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary= jsonObjMinutely.getString("summary");
String icon= jsonObjMinutely.getString("icon");
JSONArray jsonArrayMinutelyData = jsonObjMinutely.getJSONArray("data");
for(int i=0; i<jsonArrayMinutelyData .length(); i++){
JSONObject tempData = jsonArrayMinutelyData.get(i);
long time = tempData.getLong("time");
//parse the remaining object pairs.
}
JSONObject jsonObjHourly= forecast.getJSONObject("hourly");
//similar to minutely parsing. Only has more and different data
JSONObject jsonObjDaily= forecast.getJSONObject("daily");
//similar to hourly parsing.
JSONObject jsonObjFlags= forecast.getJSONObject("flags");
//It has 5 array and 1 string object so parse accordingly.
I have added the parsing logic please save the data accordingly and use it.

You may parse the minutely at wrong path. see code below (tested).
try {
// jsonString from https://api.forecast.io/forecast/8162461ea194cb97c80209d6edf4df94/37.8267,-122.423
String jsonString = "";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject minutely = jsonObject.getJSONObject("minutely");
Log.d("JSON", "minutely: " + minutely);
String summary = minutely.getString("summary");
Log.d("JSON", "summary: " + summary);
JSONArray datas = minutely.getJSONArray("data");
for (int i = 0; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
Log.d("JSON", "data # index" + i + ": " + data);
}
} catch (JSONException e) {
e.printStackTrace();
}
output:
D/JSON ( 1590): minutely: {"summary":"Partly cloudy for the hour.","icon":"partly-cloudy-night","data":....
D/JSON ( 1590): summary: Partly cloudy for the hour.
D/JSON ( 1590): data # index0: {"time":1443331140,"precipIntensity":0,"precipProbability":0}
D/JSON ( 1590): data # index1: {"time":1443331200,"precipIntensity":0,"precipProbability":0}
....

This is not a valid json.
You can check your logcat for the exception thrown.
If the exception has been caught, try and print stack trace. That will help you know where the problem is.

i check your json again and it should be one of two cases
the first is like
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
and the solution will be look like.
JSONObject minutely = forecast.getJSONObject("minutely");
second it like
[
{
"latitude": 37.8267,
"longitude": -122.423,
"timezone": "America/Los_Angeles",
"offset": -7,
"currently": {
"time": 1443322196,
"summary": "Partly Cloudy",
"icon": "partly-cloudy-night",
"nearestStormDistance": 13,
"nearestStormBearing": 77,
"precipIntensity": 0,
"precipProbability": 0,
"temperature": 63.94,
"apparentTemperature": 63.94,
"dewPoint": 55.46,
"humidity": 0.74,
"windSpeed": 8.59,
"windBearing": 277,
"visibility": 8.51,
"cloudCover": 0.44,
"pressure": 1010.39,
"ozone": 261.48
},
"minutely": {
"summary": "Partly cloudy for the hour.",
"icon": "partly-cloudy-night",
"data": [
{
"time": 1443322140,
"precipIntensity": 0,
"precipProbability": 0
}
]
}
}
]
and solution will be that you should change your forecast object to be JsonArray.
You can test the validation of your json here

Minutely is not JSONArray its JSONObject.
Try this:-
JSONObject forecast = new JSONObject(jsonData);
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary = jsonObjMinutely.getString("summary");

Your minutely is invalid JSON..
Let's take a look at that closer:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
It doesn't have a closing bracket for both the minutely's JSONObject and data's JSONArray. Also, it has a comma where "data" array actually contains one element.
Fixing those to:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
} ]
}
Then your "minutely" object is now valid. This is first.
Then to get your "minutely"
...
JSONObject forecast = new JSONObject(jsonData);
JSONObject minutely = forecast.getJSONObject("minutely");

parsing json is very easy now with android studio. In android studio install plugin GSON then create model class and enter 'alt+insert' it will popup for generator then select GSONFormat and paste your json there you will get model class for your json. In activity where you get json response do this
Gson gson = new Gson();
YourModelClass object = gson.fromJson(jsonResponseObject.toString(), YourModelClass.class);
Here you succefully parsed json. Now its time to use your model class to get data whereever you want it

Please edit your code like below
JSONObject currently = forecast.getJSONObject("currently");
Double humidity = currently.getDouble("humidity");
Long time = currently.getLong("time");
String icon = currently.getString("icon");
Double precipChance = currently.getDouble("precipProbability");
Double temp = currently.getDouble("temperature");
String timezone = forecast.getString("timezone");
JSONObject minutely = forecast.getJSONObject("minutely");
Have a look at below link for complete example of Json Parsing
https://www.dropbox.com/s/q6cjifccbbw9nl1/JsonParsing.zip?dl=0

Related

Getting value of inner object of json

I am a beginner in android coding. I am working on an app which gets data from php web service in JSON format, but I am not able to correctly parse it.
JSON returned looks like this:
{
"posts": [
{
"post": {
"Id": "1",
"Title": "Captain America",
"Lang": "ENG"
}
}
]
}
Android code:
JSONObject job = new JSONObject(json);//json is the string returned by web service
jObj = job.getJSONArray("posts");
JSONObject c = jObj.getJSONObject(0);
String title = c.getString("Title");
But I get a JSON exception:No value for Title
I cant figure out whats going wrong.
You have
{ //JSONObject job = new JSONObject(json); ok
"posts": [ // jObj = job.getJSONArray("posts"); ok
{ // JSONObject c = jObj.getJSONObject(0) ok
"post": { // forgot about jsonobject post // missed JSONObject post = c.getJSONObject("post")
"Id": "1",
"Title": "Captain America",
Change to
JSONObject c = jObj.getJSONObject(0);
JSONObject post = c.getJSONObject("post");
String title = post.getString("Title");
JSONObject job = new JSONObject(json);//json is the string returned by web service
JSONArray jar=job.getJSONArray("posts");
for (int i=0;i<jar.length();i++)
{
job=jar.getJSONObject(i);
job=jat.getJSONObject("post");
title=job.optString("Title");
}
You forget to get "post" value

How to extract values from JSONObject in android

1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");

JSON Handling Quick

Hey guys this is the first time I am doing JSON and I have gotten the json from the server. Now my only question is how do I take the data.
The JSON includes
[
{
"name": "Joe Smith",
"employeeId":1,
"company": "ABC",
"phone": {
"work": "555-555-5555",
"home": "666-666-6666",
"mobile": "777-777-7777"
}
},
{
"name": "Does Smith",
"employeeId":2,
"company": "XYZ",
"phone": {
"work": "111-111-1111",
"home": "222-222-2222",
"mobile": "333-333-3333"
}
}
]
jsonData is my string of the JSON
Currently I have:
JSONObject json = new JSONOBject(jsonData);
JSONObject data = json.getJSONObject(*******)
JSONArray phones = data.getJSONArray("phone");
not sure what to put on the second line. Also, what is the best way to group the information.
Please make it easy to understand, not exactly a professional yet haha
Thanks!
Your first line is wrong because current string is JSONArray of JSONObject's so get data from current string as:
JSONArray json = new JSONArray(jsonData);
for(int i=0;i<json.length();i++){
JSONObject data = json.getJSONObject(i);
// get name,employeeId,... from data
String str_name=data.optString("work");
//...
JSONObject jsonobjphones = data.getJSONObject("phone");
// get work from phone JSONObject
String str_work=jsonobjphones.optString("work");
//....
}
Try this
List list=new ArrayList();
JSONObject jObject = new JSONObject(str_response_starter);
JSONArray json_array_item_id = jObject.getJSONArray("itemid");
System.out.println("json array item id"+json_array_item_id);
JSONArray json_array_item_name = jObject.getJSONArray("itemname");
System.out.println("json array item name"+json_array_item_name);
JSONArray json_array_item_type = jObject.getJSONArray("type");
System.out.println("json array item type"+json_array_item_type);
JSONArray json_array_item_cost = jObject.getJSONArray("cost");
System.out.println("json array item cost"+json_array_item_cost);
Now
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
System.out.println(" value of k"+k);
v = kvPairs.get(k);
System.out.println(" value of v"+v);
In JSON, [] represents JSONArray, {} represents JSONObject. In your JSON string, it starts with [, so you need to start with JSONArray:
JSONArray people = new JSONArray(jsonData);
And then you'll notice that each person is a JSONObject, so now you need to loop them in order to get their information:
for(int i=0;i<people.length();i++){
JSONObject person = people.getJSONObject(i);
JSONObject phones = person.getJSONObject("phone"); //phone is also a JSONObject, because it starts with '{'
String workPhone = phones.get("work");
}

Recieving json array and saving in variables. Android

So I am receiving a JSON array in an httpresponse. The array consists of the following objects/variables.
{"sessid":"vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8","session_name":"SESS88cdfb2f1c420898","user":{"uid":"60","name":"abc","theme":"","signature":"","signature_format":"filtered_html","created":"13082976","access":"1386287","login":1386211,"status":"1","timezone":null,"language":"","picture":null,"data":{"mimemail_textonly":0},"roles":{"2":"authenticated user","5":"centre user"},"field_centre_reference":{"und":[{"nid":"256"}]},"field_first_name":{"und":[{"value":"web","format":null,"safe_value":"web"}]},"field_surname":{"und":[{"value":"services","format":null,"safe_value":"services"}]},"bounce_mail_blocked":false,"force_password_change":"0"}}
Now I want to receive all these objects/strings in separate variables. Like i want to store the "sessid" in a variable String session_id. And so on. I can get the first two (i.e. sessid and session_name) in a simple way with the help of the following code.
response = client.execute(httppost);
BasicResponseHandler handler = new BasicResponseHandler();
String data = handler.handleResponse(response);
jObj = new JSONObject(data);
sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
session_name = jObj.getString("session_name");
Log.d("session_name", session_name);
But since I am a noob at Android, I don't know how to get the rest of the data to be saved in variables. The upcoming data cannot be saved in a simple way.
Try with this:
JSONObject j_user = jObj.getJSONObject("user");
String uid = j_user.getString("uid");
...
//And so on with the rest of the fields
{ // json object node
"sessid": "vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8",
"session_name": "SESS88cdfb2f1c420898",
"user": { // json object user
"uid": "60", // string
"name": "abc",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "13082976",
"access": "1386287",
"login": 1386211,
"status": "1",
"timezone": null,
"language": "",
"picture": null,
"data": { // json object data
"mimemail_textonly": 0 //string
},
....// rest of the json
{ represents json object node
[ represents json array node
To parse
JSONObject jObj = new JSONObject(load());
String sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("uid");
Log.d("sessid obj", uid);
To parse data
"data": {
"mimemail_textonly": 0
},
JSONObject data= user.getJSONObject("data");
Log.i(".......",""+data.getString("mimemail_textonly"));
To parser field_centre_reference
"field_centre_reference": { // json object field_centre_reference
"und": [ // json array und
{ // json object node
"nid": "256" //string
}
]
},
JSONObject field= user.getJSONObject("field_centre_reference");
JSONArray jr = field.getJSONArray("und");
JSONObject jb1 = (JSONObject) jr.get(0);
Log.i(".......",""+jb1.getString("nid"));
Check out JacksonParser library, it provides annotations which make your work so easy. And it is one of fastest parsing libraries... You can have it here
Edit:
As an example you can take a look at one of my previous question JacksonParser databind and core cause "Found duplicate file for APK"?
You should notice that the JSON you received is a nested JSON. It is like a Map that one of the value of Map is also a Map.
In your case, there is a JSONObject contains sessid and session_name while is only string, but the "user" is also a JSONObject, so you can parse it level by level.
For more details, you can read http://www.vogella.com/articles/AndroidJSON/article.html
Try this..
Getting
"user": {
"uid": "60",
JSONObject obj_user = jObj.getJSONObject("user");
String uid = obj_user.getString("uid");
"user": {
"uid": "60",
"data": {
"mimemail_textonly": 0
}
JSONObject obj_data = jObj.getJSONObject("data");
String mimemail_textonly = obj_user.getString("mimemail_textonly");
JSONObject obj_roles = jObj.getJSONObject("roles");
String two = obj_roles.getString("2");
"field_centre_reference": {
"und": [
{
"nid": "256"
JSONObject obj_field_centre_reference = jObj.getJSONObject("field_centre_reference");
JSONArray ary_und = obj_field_centre_reference.getJSONArray("und");
JSONObject objve = ary_und.getJSONObject(0);
String nid= objve.getString("nid");

Parsing JSON object in android

I have JSON object as follows:
[
{
"Project": {
"id": "1",
"project_name": "name"
},
"AllocationDetail": [
{
"id": "1",
"project_id": "1",
"team_name": "ror",
"week_percentage_work": "50",
"in_today": "1",
"actual_hours": "30",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:48:33",
"modified": "2012-01-13 15:48:33"
},
{
"id": "2",
"project_id": "1",
"team_name": "php",
"week_percentage_work": "40",
"in_today": "2",
"actual_hours": "50",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:49:40",
"modified": "2012-01-13 15:49:40"
}
]
}
]
I want to parse data in android and store it into DB, but i m getting confused in Jsonobject
thanks
the best JSON Tutorial i have seen, I leared json parsing from this tutorial, hope it will help
The following is a snippet code for parsing your json string. Kindly go through it:
String response = <Your JSON String>;
String Project = null;
String AllocationDetail = null;
try {
JSONArray menuObject = new JSONArray(response);
for (int i = 0; i< menuObject.length(); i++) {
Project = menuObject.getJSONObject(i).getString("Project").toString();
System.out.println("Project="+Project);
AllocationDetail = menuObject.getJSONObject(i).getString("AllocationDetail").toString();
System.out.println("AllocationDetail="+AllocationDetail);
}
JSONObject jsonObject = new JSONObject(Project);
String id = jsonObject.getString("id");
System.out.println("id="+id);
String project_name = jsonObject.getString("project_name");
System.out.println("project_name="+project_name);
JSONArray jArray = new JSONArray(AllocationDetail);
for (int i = 0; i< jArray.length(); i++) {
String team_name = jArray.getJSONObject(i).getString("team_name").toString();
System.out.println("team_name="+team_name);
String week_percentage_work = jArray.getJSONObject(i).getString("week_percentage_work").toString();
System.out.println("week_percentage_work="+week_percentage_work);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There are two ways for parsing JSON
Google GSON
JSON
When your content of JSON is too complex and long enough you can prefer usin GSON its much easier to maintain than JSON parsing each value manually.
Use jsonlint.com to read your json better. It appears that the json that you have copied here is invalid.
String response = <Your JSON String>; // add your Json String here
response = response.replace("[","").replace("]",""); // Just remove all square braces
JSONObject json = new JSONObject(response); //Convert the Json into Json Object
JSONObject jProject = json.getJSONObject("Project"); // get your project object
String project_id = jProject.getString("id"); // Get the value of Id
String project_name = jProject.getString("project_name"); // get the value of Project_name
The above code can be use many times as you want to parse the Json.
I know its too late, but It may help many people who are trying to find the same answer.
I was trying to find the same solution, but it was too hard to use the Accepted answer because of too many lines of codes, But I got the same results with hardly few lines of codes.

Categories

Resources