Error parsing JSON data in android [duplicate] - android

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.

Related

How can i get the value that are inside several arrays when getting json data? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I'm making an android app to control my AC, in my app i would like to know the temperature outside. I have an json link to the local weather forecast provider and it have the temperature value I'm looking for.
Link to JSON (https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json)
My problem is that I don't know how to get to the temperature value when it´s inside several arrays. The object I'm looking for is inside "timeSeries" -> "parameters" -> and the name is "t" and it is that "value" I want (it´s the temperature in Celsius).
I have tried several ways of fix it but obvious I'm not there :). I insert a part of my code so you can see what I'm trying.
#Override
public void onResponse(Call call, Response response) throws IOException {
String forecastData;
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
forecastData = getCurrentDetails(jsonData);
}
} catch (IOException e) {
Log.e(TAG, "IO Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "JSON Exception caught:", e);
}
}
private String getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray currently = forecast.getJSONArray("timeSeries");
String currentTemp = "";
return currentTemp;
}
});
It´s in the getCurrentDetails i want to get the temperature and then return it.
If you want to get the latest temperature from the json data
In getCurrentDetails() method:
JsonObject forecast = new JsonObject(jsonData);
JsonArray timeSeries = forecast.getJsonArray("timeSeries");
JsonObject current = timeSeries.getJsonObject(0);
JsonArray parameters = current.getJsonArray("parameters");
JsonObject firstParam = parameters.getJsonObject(parameters.length() - 1);
JsonArray values = firstParam.getJsonArray("values");
String tempValue = values.getString(0);
//You can now return the tempValue
If you want to get all temperatures in the jsonData
In getCurrentDetails() method:
JsonObject forecast = new JsonObject(jsonData);
JsonArray timeSeries = forecast.getJsonArray("timeSeries");
ArrayList<String> temps = new ArrayList<>();
for(int i=0; i < timeSeries.length(); i++){
JsonObject current = timeSeries.getJsonObject(i);
JsonArray parameters = current.getJsonArray("parameters");
JsonObject firstParam = parameters.getJsonObject(parameters.length() - 1);
JsonArray values = firstParam.getJsonArray("values");
String tempValue = values.getString(0);
temps.add(tempValue);
}
// You can now return the temps.
//NOTE that in this case, your
//getCurrentDetails() method should
//return ArrayList<String> not String.

How can I get a JsonObject from a URL in 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);
}

How to break up string response?

I am receiving a String response from the following #Override method
#Override
publc void onSuccess(String response) {
....
}
The conflict I am facing is that I do not know how to break up this response into key value pairings. This is an example of the response.
{"action":{"generic_message":"test generic message"},"domains":{"key_example_one":"https:/google.com","api_root_url":"https://test.com/new/0.2/json"},"page":null}}
I have attempted to convert the string to a JSONObject, and then adding the JSONObjects to a JSONArray.
JSONObject mJObj;
try {
mJObj = new JSONObject(response);
JSONArray mJArry = mJObj.getJSONArray("action");
for (int i = 0; i < mJArry.length(); i++) {
JSONObject newObj = mJArry.getJSONObject(i);
String test2 = newObj.getString("generic_example_for_all_platforms");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: I am getting JSON exception that JSONArray cannot be converted to JSONObject, for the following line.
JSONArray mJArry = mJObj.getJSONArray("action");
Thanks in advante
You do want to read more about JSON here.
The first thing to know is that {} is equal to a Json Object and [] is equal to a Json Array.
try {
JSONObject mJObj = new JSONObject(response);
JSONObject actionJsonObject = mJObj.getJSONObject("action");
String generic_message = actionJsonObject.getString("generic_message");
JSONObject domainsJsonObject = mJObj.getJSONObject("domains");
String key_example_one = domainsJsonObject.getString("key_example_one");
String api_root_url = domainsJsonObject.getString("api_root_url");
String page = mJObj.getString("page");
} catch (JSONException e) {
e.printStackTrace();
}
Check out Gson.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
EDIT:
Just saw that you can't move to other Json processors. The property 'action' holds a JSONObject not a JSONArray. What about JSONObject jsonObject = mJObj.getJSONObject("action").

How to get particular value from JSON response in Android?

I want to get the value of "result" from the below JSON response and store it locally.Here's the code:
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
My Response :
{"response":
[{
"name":"ajay",
"class":"7",
},
{
"rank":1
}],
"date":
{
"startdate":2/12/2012,
},
"result":"pass"
}
You need to create a JSON Object from json String, you get and then retrieve its data:
JSONObject json= new JSONObject(responseString); //your response
try {
String result = json.getString("result"); //result is key for which you need to retrieve data
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope it helps.
Please provide correct and full JSON response. So I can show you the way to parse the JSON :
String jsonStr; // hold your JSON response in String
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("response"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("name");
}
// If you have object
String result = json.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Try like this...
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject json= new JSONObject(jsonStr); //your json response
String result = json.getString("result"); //result data
} catch (JSONException e) {
e.printStackTrace();
}
}
}

storing json parsed values as string in array

I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}

Categories

Resources