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 excuted the followinf api request
https://api-v3.mbta.com/predictions?sort=arrival_time&filter%5Bstop%5D=70028%2C70029
and I am having the following parsing problem.
Failed to parse JSON
org.json.JSONException: Value [{"attributes":{"arrival_time":"2018-04-25T13:20:01-04:00","departure_time":"2018-04-25T13:20:01-04:00",
"direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null}
,"id":"prediction-36315805-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":
{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315805","type":"trip"}}},"type":"prediction"},{"attributes"
:{"arrival_time":"2018-04-25T13:26:03-04:00","departure_time":"2018-04-25T13:26:03-04:00","direction_id":0,"schedule_relationship":null,
"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315802-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315802","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:29:28-04:00","departure_time":"2018-04-25T13:29:28-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315806-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315806","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:33:00-04:00","departure_time":"2018-04-25T13:33:00-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315803-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315803","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:36:20-04:00","departure_time":"2018-04-25T13:36:20-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315807-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315807","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:44:44-04:00","departure_time":"2018-04-25T13:44:44-04:00","direction_id":0,"schedule_relationship":"ADDED","status":null,"stop_sequence":50,"track":null},"id":"prediction-ADDED-1524238424-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"ADDED-1524238424","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:00-04:00","departure_time":"2018-04-25T13:52:00-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315809-70029-140","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70029","type":"stop"}},"trip":{"data":{"id":"36315809","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T13:52:39-04:00","departure_time":"2018-04-25T13:52:39-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315757-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315757","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:00:20-04:00","departure_time":"2018-04-25T14:00:20-04:00","direction_id":0,"schedule_relationship":null,"status":null,"stop_sequence":50,"track":null},"id":"prediction-36315758-70028-50","relationships":{"route":{"data":{"id":"Orange","type":"route"}},"stop":{"data":{"id":"70028","type":"stop"}},"trip":{"data":{"id":"36315758","type":"trip"}}},"type":"prediction"},{"attributes":{"arrival_time":"2018-04-25T14:09:34-04:00","departure_time":"2018-04-25T14:09:34-04:00","direction_id":1,"schedule_relationship":null,"status":null,"stop_sequence":140,"track":null},"id":"prediction-36315810-70029-140","relationships":{"route":{"data":{"id":"
I am parsing the code like this
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
throws IOException, JSONException {
JSONObject photosJsonObject = jsonBody.getJSONObject("data");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("attributes");
for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);
GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("arrival_time"));
item.setCaption(photoJsonObject.getString("departure_time"));
item.setUrl(photoJsonObject.getString("departure_time"));
items.add(item);
}
}
could some one tell me where I am making a mistake when parsing the object.
thank you
Well, from your posted json data is an array and attributes is an object, you were trying to parse them the other way around. Try this:
JSONArray data = jsonBody.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject singleData = data.getJSONObject(i);
JSONObject attributes = singleData.getJSONObject("attributes");
GalleryItem item = new GalleryItem();
item.setId(attributes.getString("arrival_time"));
item.setCaption(attributes.getString("departure_time"));
item.setUrl(attributes.getString("departure_time"));
items.add(item);
}
As data is a JSONArray, and your photosJsonObject should be JSONArray not object, which contains the objects. Rest is ok I think.
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
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");
}
}
it gives me the error log : " org.json.JSONException: No value for tableData"
try {
JSONObject mainJson22 = new JSONObject(reply);
JSONObject jsonResult = mainJson22.getJSONObject("UserListByBusinessAreaContextResult");
JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");
// JSONArray jsonArray22 = mainJson22.getJSONArray("UserListByBusinessAreaContextResult"); // JSONArray jsonArray22 = jsonResult.getJSONArray("tableData"); Log.i("mainjson234","" + jsonArray22);
for (int i2 = 0; i2 < jsonArray22.length(); i2++) {
JSONObject objJson22 = jsonArray22.getJSONObject(i2);
the error is on line : `"JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");"
heres the json:
{
"UserListByBusinessAreaContextResult": "{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
}
The object UserListByBusinessAreaContextResult contains a string. This string is:
"{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
Do you notice the quotes? The problem is, that your WCF service returns a JSON string, not an object. So either you will have to change the WCF service to deliver an object instead, or parse that string again. Like this (not tested):
JSONObject mainJson22 = new JSONObject(reply);
JSONObject tableData = new JSONObject(
mainJson22.getString("UserListByBusinessAreaContextResult"));