Hi. How do I parse the following JSON "openweather**strong text**": - android

i use www.openweathermap.org FORECAST.
thisi the result of forecat: http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139
JSONObject coordObj = getObject("coord", jObj);
Latitude=getFloat("lat", coordObj);
Longitude=getFloat("lon", coordObj);
JSONObject coordObj = getObject("city", jObj);
id=getFloat("id", coordObj);
name=getFString("name", coordObj);
JSONObject sysObj = getObject("sys", jObj);
Country=getString("country", sysObj);
Sunrise=getInt("sunrise", sysObj));
Sunset=getInt("sunset", sysObj));
JSONObject jlist = jObj.getObject("list");
JSONObject JSONWeather = jArr.getJSONObject(0);
Condition_id==getInt("id", JSONWeather);
condition_description=getString("description", JSONWeather);
condition=getString("main", JSONWeather);
condition_icongetString("icon", JSONWeather);
JSONObject mainObj = getObject("main", jObj);
Humidity=getInt("humidity", mainObj);
Pressure=getInt("pressure", mainObj);
MaxTemp=getFloat("temp_max", mainObj);
MinTemp(getFloat("temp_min", mainObj);
Temp=getFloat("temp", mainObj);
// Wind
JSONObject wObj = getObject("wind", jObj;
Speed=getFloat("speed", wObj);
Deg=getFloat("deg", wObj);
// Clouds
JSONObject cObj = getObject("clouds", jObj);
Perc=getInt("all", cObj);
please how to loop the weather array ?

First, list is not a JsonObject it's an array, so you should get it doing:
JSONArray jlist = (JSONArray) jObj.get("list");
Depending of which library you are using the syntax can change but the logic is the same, I'm explaining using json simple lib.
after that you should iterate your list array, something like this:
for (int i = 0; i < jlist.size(); i++){
// get all your objects and your weather array
// to get your weather array the logic is the same:
JSONArray jArrayWeather = (JSONArray) jObj.get("weather");
for (int j = 0; j < jArrayWeather ; j++){
//and here you can get your id, main, description and icon using j index
JSONObject currentObj = (JSONObject) jArrayWeather.get(j);
String main = (String) currentObj.get("main");
}
}
I didn't test this code, so follow the idea and try to do it yourself. Take a look here as we can see you haven't experience with json

Here is another example. (For a different JSON format though).
try{
JSONArray list=json.getJSONArray("list");
for(int indx=0;indx<MAX_FORCAST_FRAGMENT;indx++) {
JSONArray weather = list.getJSONObject(indx).getJSONArray("weather");
String weatherIconString=setWeatherIcon(weather.getJSONObject(0).getInt("id"),
0,100);
forcastData[indx][0]=weatherIconString;
JSONObject main=list.getJSONObject(indx).getJSONObject("main");
JSONObject wind=list.getJSONObject(indx).getJSONObject("wind");
String detailsFieldString= weather.getJSONObject(0).getString("description").toUpperCase(Locale.US);
String humidityFieldString="Humidity: " + main.getString("humidity") + "%";
String windFieldString= "Wind: " + wind.getString("speed") + " Km/H";
// populate the list view//
int forecastFragmentId=getResources().getIdentifier("forcast_layout_" + (indx+1), "id", getPackageName());
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.details_field);
tv.setText(detailsFieldString);
saveData(F_DETAILS+indx,detailsFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.weather_icon);
tv.setText(weatherIconString);
saveData(F_ICON+indx,weatherIconString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.wind_field);
tv.setText(windFieldString);
saveData(F_WIND+indx,windFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.humidity_field);
tv.setText(humidityFieldString);
saveData(F_HUMIDITY+indx,humidityFieldString);
c = Calendar.getInstance();
int currentDate=c.get(Calendar.DAY_OF_MONTH);
saveTime(LAST_FORCAST_TIME,currentDate);
}
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data in renderForecastData");
}
}

Related

Why I am getting null JSON response?

I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...

I want to parse this JSON with volley but I am not able to do it

I want to parse this JSON in Volley Library. I have set everything I want to parse name of the recipe and image. Problem is that I want three recipes to be parsed at same time but here it have same Object name Recipe and I don't know how to parse same object name for three different TextViews.
Here is the JSON format: link
Here is the code I tried but it gave me one name not three different names:
try {
JSONArray list = response.getJSONArray("hits");
Log.v ("MISH", "List: " + list);
for (int x = 0; x<list.length(); x++) {
JSONObject obj = list.getJSONObject(x);
JSONObject main = obj.getJSONObject("recipe");
String label = main.getString("label");
String image = main.getString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
Try this.
And use optString in your code:
try {
if (TextUtils.isEmpty(response)) {
Toast.makeText(this, "response is null", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonObject = new JSONObject(response);
JSONArray hits = jsonObject.getJSONArray("hits");
// edited here ,add data in your code
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2
for (int i = 0; i < hits.length(); i++) {
JSONObject jo = hits.getJSONObject(i);
JSONObject recipe = jo.getJSONObject("recipe");
String label = recipe.optString("label");
String image = recipe.optString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
} catch (JSONException e) {
e.printStackTrace();
}
Edit
// If your don't have to much data in your code , you can do like this .
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2

JSONObject or JSONArray

I have data on this string, but I'm having trouble to access the individual data.
This is my code:
Log.d("Detail Outputss", "" + response.toString());
And this is the string output:
{"futsal_id":"45","info":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"description":[{"futsal_id":"45","futsal_desc":"Futsal is the fever which never ends.\r\nKathmandu futsal is - a platform, a medium of communication for our fraternity. Not just somewhere to host challenges or seek venues, but a place where we can all share and spread the luv! Here, you can find just about anything, do just about anything, and see just about anything. Unbelievable? Believe it."}],"features":[{"futsal_id":"45","futsal_feat":"Free Wifi"},{"futsal_id":"45","futsal_feat":"High Quality Grass"},{"futsal_id":"45","futsal_feat":"Canteen Facility"},{"futsal_id":"45","futsal_feat":"Friendly Environment"}],"dimension":[{"futsal_id":"45","dimension":"40m X 20m"}],"no_of_futsal":[{"futsal_id":"45","number":"1"}],"opening_hrs":[{"futsal_id":"45","open_time_id":"1","open_time":"6am","close_time_id":"15","close_time":"9pm"}],"price_weekdays_price1":[{"futsal_id":"45","price_id":"1","start_time":"6am","end_time":"12pm","price":"1200"}],"price_weekdays_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1000"}],"price_weekdays_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"1500"}],"price_weekend_price1":[{"futsal_id":"45","price_id":"1","start_time":"6pm","end_time":"12pm","price":"1500"}],"price_weekend_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1800"}],"price_weekend_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"2000"}],"phone_number_address":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"news":[{"futsal_id":"45","news_id":"7","news_title":"asdfasdfasdfasdf","news_description":"asdfashdflahsdlfasdjf;oajsd;ofjaosdijfoaisdjofajsdfja;sjdf;ajsd;fja;ksdjf;kasjd;fkja;sdjf;asjd;fajsd;fjasdjf;asjd;fjas;djf;asdf"},{"futsal_id":"45","news_id":"6","news_title":"awefasdf","news_description":"sdjf;asdf;a;sdf;asjdf;oajsd;fja;sdjf;oajsd;oifjaosdf"},{"futsal_id":"45","news_id":"5","news_title":"asdfasdf","news_description":"sadfasdfasdfasdfa"}]}
I want to get the value of each object futsal_id, futsal_name, city and others, thanks in advance!!
It is JSONArray within a JSONObject
JSONObject json = new JSONObject(response);
JSONArray info = json.getJSONArray("info");
//getting the first value.. loop it if you have more than one
JSONObject infoObject = info.getJSONObject(0);
JSONArray description = json.getJSONArray("description");
JSONObject json = new JSONObject(response);
int fustal_id =Integer.parseInt(json.getString("futsal_id"));
JSONArray inf = json.getJSONArray("info");
JSONObject info = inf.getJSONObject(0);
...
JSONObject responseObject = new JSONObject(response);
JSONArray info = responseObject.getJSONArray("info");
for(int i = 0; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
String futsal_id = obj.getString("futsal_id");
String futsal_name = obj.getString("futsal_name");
//so on
}
Be sure to catch the exceptions.

How to split this kind of data in android

Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}

Json data extracting in android

i want to extract the given json arry in android,
[{"Outofserviceday":{"outofservice":"2013-02-22"}},
{"Outofserviceday":{"outofservice":"2013-02-27"}},
{"Outofserviceday":{"outofservice":"2013-02-28"}}]
i have the code for extracting the json data like given below
[{"Requestcard":{"id":"994","userprofile_id":"14","userprofile_name":"Syed
Imran","company_name":"DLF Akruti Park, Hinjewadi, Pune,
Maharashtra","sex":"male","travel_date":"2013-02-12"}}]
in this case we can retrive the json boject using the code
JSONObject menuObject = json_data.getJSONObject("Requestcard");
and retrieve each element by
requestid= menuObject.getString("id");
But in the first case how we identify each Outofserviceday in the json array ? and How extract each data ???
you can do something like below, can create jsonArray from string json data and then can extracts json objects in a loop or so.
String json =" [{\"Outofserviceday\":{\"outofservice\":\"2013-02-22\"}}]"; //json-data which is basically a json array
JSONArray jArray = new JSONArray(json); / creating an jsonarray
for (int i = 0; i < jArray.length(); i++) {
// you can have jsonObject from json array here in the loop
}
Try this:
JSONObject json = new JSONObject(result);
JSONArray json1= json.getJSONArray("data");
if (json1.length()!=0) {
for (int i = 0; i < json1.length(); i++) {
String name = json1.getJSONObject(i).getString("name");
}
}
With the help of below code you can retrieve the value of outofservice
JSONArray jArray = new JSONArray(your data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOutOfServiceDay = jArray.getJSONObject(i);
JSONObject jobj = jOutOfServiceDay.getJSONObject("Outofserviceday");
Log.i("Required data is:", "" + jobj.getString("outofservice"));
}

Categories

Resources