How can I get a JsonObject from a URL in Android? - android

I have to a JSONObject, especially the "data" content, in Android from a WebService, then I have to print it into a ListView or a Table.
This is my JSON:
{
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}

Let
response = {
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
String status = response.get("status"); // status = 200
String status_message = response.get("status_message"); // status_message = "Direct ways found"
JSONArray message = response.getJSONArray("data");
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < message.length(); i++) {
HashMap<String, String> hm = new HashMap<String, String>();
JSONObject temp = message.getJSONObject(i);
hm.put("codice_linea",temp.getString("codice_linea"));
hm.put("partenza",temp.getString("partenza"));
hm.put("ora_partenza",temp.getString("ora_partenza"));
hm.put("arrivo",temp.getString("arrivo"));
....................................
.............................
aList.add(hm);
}
Finally all your JSON data is prased to List aList.
Then use custom Listview to show this data in Listview
Here is the full tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
Hope this solved your problem.

Try this
JSONObject jsonObject = new org.json.JSONObject(YourJsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
......
}

I assume you effort to get this Json in android , if i right try this:
Paste your example Json in Json Schema 2 Pojo , and site will generate Pojo classes
Convert your Json response to Pojo class with Gson
Add this line to your dependencies : compile 'com.google.code.gson:gson:2.4'
Convert Json result to Pojo :
Gson gson = new Gson();
YourPojo yourpojo= gson.fromJson(jsonresponse, YourPojo.class);
And handle result whatever you want .
If you didnt effort anything
Go to google and search how to handle Json in android or how to connect web service , for example you can search : HttpUrlConnection , OkHttp, Retrofit ...

What you seem wanting to do is to re-create an existing JSONObject that is contained in an array.
If you use the JSONObject from the Android tools, you can use getJSONObject and getJSONArray.
According to the Documentation:
Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise.
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
See here for more details.

You have to do something like that:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Your-url-JsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String status = response.getString("status");
String status_message = response.getString("status_message");
JSONArray jsonArray =jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
jsonArray.getJSONObject(i).getString("arrivo");
jsonArray.getJSONObject(i).getString("ora_arrivo");}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}

Related

How to get JSON data out of JSON Array?

I am using the Volley libary to understand working with JSON data, i have successfully retrieved some data and would like to know how to get the individual data out of my json array? I have tried doing what user's suggested on previous stackover flow post but only the json array data is showing up
#Override
public void downloadJson() {
final String url = "https://dog.ceo/api/breeds/image/random/2";
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("message");
Log.i("jsonArray", jsonArray.toString());
for(int i=0; i>jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(getRequest);
}
exactly i can't understand your question .
but in your code there are some problem .
in below you can see my proposal code .
for(int i=0; i<jsonArray.length(); i++)
{
Log.i("obj", jsonArray.get(i).toString());
}
in this code you can get each data from you'r JSONArray and use that URL to load image.
if this is not answer to you'r question i will be glad if you give some explanation about you'r question.
There is mistake in your for loop,
for(int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
Hope it will help!!

Android Studio: How to parse a JSON Object from Inside of a JSON Array?

I am trying to parse the following JSON data into a recycler view. In particular, I want to parse the address object to display the locationName, line1, city, state and zip, but I cant get the parsing method right.
{
"pollingLocations": [
{
"address": {
"locationName": "LITTLE LEAGUE HEADQUARTERS",
"line1": "6707 LITTLE LEAGUE DR",
"city": "SAN BERNARDINO",
"state": "CA",
"zip": "92407"
},
"notes": "",
"pollingHours": "07:00-20:00",
"sources": [
{
"name": "Voting Information Project",
"official": true
}
]
}
]
}
My issue is finding the address object. With the current code, I get a logcat error that says No value for locationName. I think this is because I first need to specify the address object to iterate through, but how do I do this? This is the current implementation that I have right now.
//fetch
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("pollingLocations");
for(int i = 0; i < array.length(); i++){
JSONObject addressObject = array.getJSONObject(i);
for (int x = 0; x < addressObject.length(); x++){
VotingLoc votingLoc = new VotingLoc(addressObject.getString("locationName"),
addressObject.getString("line1"),
addressObject.getString("city"),
addressObject.getString("state"),
addressObject.getString("zip"),
addressObject.getString("pollingHours"));
votingList.add(votingLoc);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Locat Error:
Is there an easier way of doing this? I believe the code for my rvadapter class and is correct and the error is in this method, but If you want to see any other code, let me know.
By getting first node in array you have obtained address node so no need to run loop there, address object is not an array you can get values directly. Try something like this:
JSONArray array = object.getJSONArray("pollingLocations");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String locationName = jsonObject.getJSONObject("address")
.getString("locationName");
Log.d("locationName", locationName);
JSONArray sourcesArray = jsonObject.getJSONArray("sources");
// run loop to get values from this array
for (int j = 0; j < sourcesArray.length(); j++){
JSONObject source = sourcesArray.getJSONObject(j);
String name = source.getString("name");
}
}
Another way could be using a json parser like gson (https://github.com/google/gson) or jackson (https://github.com/FasterXML/jackson). This may be a bit overhead if your only goal is to show these few values, as you must create some java classes, you may only need for parsing.

parsing JSON string for an array in Java

I am writing an Android application that pulls JSON data from an SQL db.
In my Async Task class, I receive a JSON string from an HTTP request and I assign it to a JSONObject. This string contains various data, including an array of coordinates which I need. After that, I do obj.getJSONArray("coordinates"); As soon as I do that, my application throws an exception:
org.json.JSONObject cannot be converted to JSONArray in android
I am following this post's approach to solve my issues but with no luck:
org.json.JSONObject cannot be converted to JSONArray in android
I feel like I need to iterate over my JSON string until I see that array. I will post the string data below.
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(address);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray deviceJsonArray = obj.getJSONArray("coordinates"); //ERROR OCCURS HERE!
// looping through All Devices
for (int i = 0; i < deviceJsonArray.length(); i++) {
JSONObject json = deviceJsonArray.getJSONObject(i);
//String DeviceID = c.getString("id");
// longitude = json.getDouble("longitude");
// latitude = json.getDouble("latitude");
Device device = new Device();
device.setName(receivedDeviceName);
//Adding the information to the array.
coordinatesArray.add(device);
}
//Log.e(TAG, "arraylist: " + coordinatesArray);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
JSON string value:
{"data":{"type":"gps","total_distance":18,"coordinates":[{"latitude":49.169209,"longitude":-122.990952,"time":"12:02:38 AM"},{"latitude":49.16922,"longitude":-122.990959,"time":"2:42:33 PM"},{"latitude":49.1693,"longitude":-122.988098,"time":"5:16:33 PM"},{"latitude":49.170979,"longitude":-122.968239,"time":"5:18:33 PM"},{"latitude":49.174992,"longitude":-122.962502,"time":"5:20:33 PM"},{"latitude":49.17688,"longitude":-122.95768,"time":"5:22:33 PM"},{"latitude":49.182232,"longitude":-122.960297,"time":"5:24:33 PM"},{"latitude":49.18581,"longitude":-122.950813,"time":"5:26:33 PM"},{"latitude":49.188869,"longitude":-122.945969,"time":"5:28:33 PM"},{"latitude":49.197689,"longitude":-122.948502,"time":"5:30:33 PM"},{"latitude":49.20216,"longitude":-122.947418,"time":"5:32:33 PM"},{"latitude":49.2071,"longitude":-122.949593,"time":"5:34:33 PM"},{"latitude":49.213051,"longitude":-122.938522,"time":"5:36:33 PM"},{"latitude":49.215462,"longitude":-122.93399,"time":"5:38:33 PM"},{"latitude":49.216381,"longitude":-122.932297,"time":"5:40:33 PM"},{"latitude":49.218769,"longitude":-122.92791,"time":"5:42:33 PM"},{"latitude":49.221062,"longitude":-122.923653,"time":"5:44:33 PM"},{"latitude":49.227119,"longitude":-122.912392,"time":"5:46:33 PM"},{"latitude":49.234489,"longitude":-122.89872,"time":"5:48:33 PM"},{"latitude":49.235699,"longitude":-122.894608,"time":"5:50:33 PM"},{"latitude":49.241928,"longitude":-122.89257,"time":"5:52:33 PM"},{"latitude":49.241871,"longitude":-122.89016,"time":"6:02:33 PM"}]}}
Could someone see what I am doing wrong or recommend a fix please?
Try this instead:
JSONObject obj = new JSONObject(jsonStr);
JSONObject objData = obj.getJSONObject("data");
JSONArray deviceJsonArray = objData.getJSONArray("coordinates");
The "coordinates" JSONArray is one element deeper in your JSON structure

Error parsing JSON data in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
Facing JSONException while parsing JSON String
Exception :
org.json.JSONException: Value anyType of type java.lang.String cannot be converted to JSONArray
Code snippet.
try {
androidHttpTransport.call(Soap_Action1, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
String resp=response.toString();
Log.d("resp",response.toString());
// newwwwww
try {
JSONArray jsonArray = new JSONArray(resp);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
System.out.println(c.getInt("MST_BloodGroupID"));
System.out.println(c.getString("BloodGroup_Name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
response.toString() is below:
anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{};
element=anyType{}; }; }; }; }; }; }; };
diffgram=anyType{DocumentElement=anyType{Table=anyType{MST_BloodGroupID=1;
BloodGroup_Name=A+; }; Table=anyType{MST_BloodGroupID=2;
BloodGroup_Name=A-; }; Table=anyType{MST_BloodGroupID=3;
BloodGroup_Name=B+; }; Table=anyType{MST_BloodGroupID=4;
BloodGroup_Name=B-; }; Table=anyType{MST_BloodGroupID=5;
BloodGroup_Name=AB+; }; Table=anyType{MST_BloodGroupID=6;
BloodGroup_Name=AB-; }; Table=anyType{MST_BloodGroupID=7;
BloodGroup_Name=O+; }; Table=anyType{MST_BloodGroupID=8;
BloodGroup_Name=O-; }; }; }; }
private class GetCategories extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
System.out.println(catObj.getInt("id"));
System.out.println(catObj.getString("name"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
Your response.toString() is not returning data that is valid JSON. A quick way to check if your strings are ever valid JSON is to plug it into this site: http://jsonviewer.stack.hu/
If it's valid, you can switch over to the viewer tab and visualize your json to make sure your code is checking for JSONArrays and JSONObjects in relation to the brackets and curly braces correctly, most errors I've experienced with parsing JSON stem from me just misreading my dataset. The site will shout loudly at you if it's invalid, as it does with your data.
I'd recommend using the GSON library to create your JSON data. After importing it into your project, you can use it like:
Gson gson = new Gson();
SoapObject response = (SoapObject) envelope.getResponse();
String resp = gson.toJson(response);
Beyond that your approach to creating JSON objects and arrays from the string data seems to be correct.
You can't convert the String to JSONArray becayse the Strings isn't Array its an JSONObject.
try to convert the String to JSONObject the get the array from the JSONObject using it's key.

how to convert a string that contain array element into JSONArray

I've been experiencing some problems for quite some time trying to load a string that contains an array into a JSONArray.
i get the following string from a web-service which contains the movies array:
{"total":3,"movies":[],"links":{......}"}
i'm looking to convert this array into a JASONArray and show it using a list view.
i'm using the following code and it not working....
protected void onPostExecute(String result) {
Log.d(TAG, "result: " + result);
if (result==null || result.length()==0){
// no result:
return;
}
//clear the list
moviesList.clear();
try {
//turn the result into a JSON object
Log.d(TAG, "create responseObject: ");
JSONObject responseObject = new JSONObject(result);
Log.d(TAG, responseObject.toString());
// get the JSON array named "movies"
JSONArray resultsArray = responseObject.getJSONArray("movies");
Log.d(TAG, "JSONArray lenght: " + resultsArray.length());
// Iterate over the JSON array:
for (int i = 0; i < resultsArray.length(); i++) {
// the JSON object in position i
JSONObject movieObject = resultsArray.getJSONObject(i);
Log.d(TAG, "movieObject (from array) : " + movieObject.toString());
// get the primitive values in the object
String title = movieObject.getString("title");
String details = movieObject.getString("synopsis");
//put into the list:
Movie movie = new Movie(title, details, null,null);
//public Movie(String title, String details, String urlnet, String urldevice) {
moviesList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
//refresh listView:
adapter.notifyDataSetChanged();
}
I was hoping a post here would help me solve the problem.
Change this:
JSONObject responseObject = new JSONObject(result);
to this:
JSONObject responseObject = (JSONObject) JSONValue.parse(result);
and then you can get your JSONArray.

Categories

Resources