My server returns a JSON object via the body of an HTTP POST response, but I get the this error when my app tries to convert the string into a JSONObject:
06-02 09:05:34.380: E/JSONException_MyAppService(19913): org.json.JSONException: Value {"VALS":{"VAL1":"hello","VAL2":"hello2","VAL3":"hello3"}} of type java.lang.String cannot be converted to JSONObject
It looks like my server is returning a acceptable JSON encoded string, but it just won't convert to a JSONObject. I even changed the content-type of the server's response header to "application/json". Please help me fix this, I've been trying all day.
EDIT- I use the following code:
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
I also tried imran khan's suggestion:
try {
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("VALS");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("VAL1");
String token1 = oj.getString("VAL2");
String token11 = oj.getString("VAL3");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
:'( :'(
How are you doing it? It should work with:
JSONObject object = new JSONObject (yourString);
You can convert string to json as:
String str="{\"VALS\":{\"VAL1\":\"hello\",\"VAL2\":\"hello2\",\"VAL3\":\"hello3\"}}";
try {
JSONObject result = new JSONObject(str);
JSONObject resultf = result.getJSONObject("VALS");
Toast.makeText(this, resultf.getString("VAL1").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL2").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL3").toString(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONObject object2 = result.getJSONObject("VALS");
String token = object2.getString("VAL1");
String token = object2.getString("VAL2");
String token = object2.getString("VAL3");
}
}
catch (Exception e) {
}
I FIXED IT! It was entirely my server's fault. It turned out that my server was responding incorrectly. What happened was there was a bug within the web framework and after updating to the latest version, the problem solved itself. I'm guessing the old version of the web framework returned the incorrect content-type response header, or used some weird encoding.
So everyone's Java code here should be 100% correct, because Java was not at fault here. THANKS FOR ALL YOUR EFFORT!
Miguel's answer was the closest explanation, so I will accept his answer.
Related
Am new to android development am making simple login application using volley and getting json response from server like this:
json response:-
{"loginResult":"{\"UserLoginID\":864,\"UserID\":864,\"EmployeeCode\":\"PI4264\",\"Password\":\"XXXX\",\"IsPasswordChanged\":false,\"ModuleName\":\"XXX\",\"ModuleID\":1,\"EmployeeName\":\"XXXX \"}"}
When i try to parse this jsonobect am getting :
Unterminated object at 19 jsonexception so far what i have tried is to parse is
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
int yogs=yog.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
don't know where am making mistake can anybody teach me am i doing it in right way!!!
You should change your code to this:
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
I executed the code and didn't get the error:
JSONObject yog = new JSONObject("{\"loginResult\":\"{\\\"UserLoginID\\\":864,\\\"UserID\\\":864,\\\"EmployeeCode\\\":\\\"PI4264\\\"," +
"\\\"Password\\\":\\\"XXXX\\\",\\\"IsPasswordChanged\\\":false,\\\"ModuleName\\\":\\\"XXX\\\",\\\"ModuleID\\\":1,\\\"EmployeeName\\\":\\\"XXXX " +
"\\\"}\"}");
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), String.valueOf(yogs), Toast.LENGTH_SHORT).show();
You are making an un-necessary string sanitization.
Just remove replaceAll command. and use following code :
try {
JSONObject yog = new JSONObject(response);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
System.out.println(yogs);
}
catch (JSONException e) {
e.printStackTrace();
}
This should work fine after that.
I try to issue a POST request with ClientResource, I'm able to retrieve the response STATUS, I also want to get the response body when I get an exception.
Here is my code:
public static Pair<Status, JSONObject> post(String url, JSONObject body) {
ClientResource clientResource = new ClientResource(url);
try {
Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);
String responseBody = response.getText();
Status responseStatus = clientResource.getStatus();
return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
} catch (ResourceException e) {
logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
//TODO - how do I get here the body of the response???
} catch (IOException |JSONException e) {
throw e;
} finally {
clientResource.release();
}
}
Here is the code that my server resource returns in case of failure
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
put("result", "failed to execute") );
return response;
I try to catch the "result" with no success
In fact, the getResponseEntity method returns the content of the response. It corresponds to a representation. You can wrap it by a JsonRepresentation class if you expect some JSON content:
try {
(...)
} catch(ResourceException ex) {
Representation responseRepresentation
= clientResource.getResponseEntity();
JsonRepresentation jsonRepr
= new JsonRepresentation(responseRepresentation);
JSONObject errors = jsonRepr.getJsonObject();
}
You can notice that Restlet also supports annotated exceptions.
Otherwise I wrote a blog post about this subject: http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/. I think that it could help you.
Thierry
First of all please look at my code below:
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("oauth_token", accessToken));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet userInfoRequest = new HttpGet(id + "?" + queryString);
DefaultHttpClient defaultHttpClientclient = new DefaultHttpClient();
HttpResponse userInfoResponse;
try {
userInfoResponse = defaultHttpClientclient.execute(userInfoRequest);
String responseBody = EntityUtils.toString(userInfoResponse.getEntity());
System.out.println("User info response: " + responseBody);
System.out.println("");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got an access token from Salesforce. Now I request user's information via that token. In the responseBody I got all infomation of that user like username, id, language,... Now I need to take only username from the response. What should I do to take it?
The response is likely in JSON. If so you can parse the data you need. I won't repost the code, instead please see: How to parse JSON in Java
JSONObject responseJSON = new JSONObject(EntityUtils.toString(userInfoResponse.getEntity());
String username = responseJSON.getString("username");
Having problems parsing this JSON data in my Android App :
[{"personid":20,"personName":"Ross Gallagher update3","email":"ross_gallagher#rossgallagher.co.uk","birthday":{"date":"2013-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"anniversary":{"date":"1900-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"Credit":2}]
The error I am getting is:
W/System.err: org.json.JSONException: Value [{"birthday":{"date":"2013-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"anniversary":{"date":"1900-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"email":"ross_gallagher#rossgallagher.co.uk","personName":"Ross Gallagher update8","Credit":2,"personid":20}] of type org.json.JSONArray cannot be converted to JSONObject
My JSON Parser code is:
public JSONObject getJSONFromUrl(String url)
{
HttpEntity httpEntity = null;
JSONObject respObject = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(httpEntity != null){
try {
respObject = new JSONObject(EntityUtils.toString(httpEntity));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//....
}
// return JSON
return respObject;
}
All I need is to pull out the Birthday details from this JSON object along with the name, email, credits and anniversary.
Any advice would be appreciated!
Change
respObject = new JSONObject(EntityUtils.toString(httpEntity));
to
respObject = new JSONArray(EntityUtils.toString(httpEntity));
ofcourse respObject has to be an JSONArray
The problem is with your JSON String. You need to remove the square brakets [] .
Square brakets are used to refer array elements. The JSON parser will try to convert it as array object as json data are inside square braket.
Accept my answer if it helps you.
Since the object you are trying to parse is actually a JSONArray and not JSONObject.. So you get JSONObject from that JSONArray like
JSONArray jsonArray = new JSONArray(EntityUtils.toString(httpEntity));
JSONOject jsonObject = jsonArray.getJSONObject(0);
from this jsonObject you would get birthday details...
i am trying to Json parsing in my android app the link is https://www.buzzador.com/apps/present_software/webservice/index.php?op=ProductQ&campaign_id=607&userid=10776
when i put it into Json object it gives errors to me
error is :
08-31 14:40:52.281: WARN/System.err(416): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
public static String getmyproductquestiondetails(String userid,
String campaignid) {// https://www.buzzador.com/apps/present_software/webservice/index.php?op=EducationResult&userid=1&questionid=1,2,3&answergivenbyuser=1,1,0
String data = null;
try {
URL url = new URL(
"http://dignizant.com/buzz/webservice/index.php?op=getProductQuestion&userid="
+ userid + "&campaign_id=" + campaignid);
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Utils utils = new Utils();
try {
data = utils.convertStreamToString(http.getInputStream());
System.out.println("getproduct details response :: " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
data = e.toString();
}
return data;
}
try {
JSONObject jo = new JSONObject(response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());
Had similar problem. At first my app was working great on both androids 4.0+ and 4.0- (2.3.3 2.2 etc). after a revision i have that problem. JSonarray could parse on 2.3.3
PROBLEM: Json STRING (response from server) comes with a character ' in front
so actual response= '[{"1":"omg"}] and not the correct one [{"1":"omg"}]
Solution:
if string dosent start with [ then edit response string (remove the ' character)
if (result.startsWith("["))
{
}
else
{
result= result.substring(1);
}
after then everything worked fine for me
If you are a using json-lib-2.4 as library, which I assume, you can parse strings with :
JSONSerializer.toJSON(yourString).toString()
instead of using the JsonObject class
To remove character like (\n) or unwanted character in json string used commons-lang3:3.4 library in program . i used this class to remove unwanted character in json string "StringEscapeUtils.unescapeJava(string)".
this will help you.