0

I have faced a problem, a valid JSON string cannot become a JSON object.

when am calling my url from browser its returning with valid JSON string. Please Check

public void initializeHttpClient() { httpclient = new DefaultHttpClient(); nameValuePairs = new ArrayList(2); }

public JSONObject sendHttpRequest(String url) {
    try {
        postRequest = new HttpPost(url);
        postRequest.setHeader("Content-type", "application/json");
        postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
        httpResponse = httpclient.execute(postRequest);
        httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            String responseString = EntityUtils.toString(httpEntity);

// here the problem is occuring..

            JSONObject responseObject = new JSONObject(responseString);
            return responseObject;
        }
    } catch (Exception e) {
        e.getMessage();
    }
    return null;
}

public JSONObject getLogin(String serviceUrl,String o_email, String o_password,String o_user_id, String o_network_type, String o_format) {
    initializeHttpClient();
    if(serviceUrl!=null){
        nameValuePairs.add(new BasicNameValuePair("login_email",o_email));
        nameValuePairs.add(new BasicNameValuePair("password",o_password));
        nameValuePairs.add(new BasicNameValuePair("user_id",o_user_id));
        nameValuePairs.add(new BasicNameValuePair("network_type",o_network_type));
        nameValuePairs.add(new BasicNameValuePair("format",o_format));
        return sendHttpRequest(serviceUrl);
    }
    return null;
}
4
  • Programming questions should be asked in StackOverflow.com. This question will be moved by a mod later. :) Commented Jan 8, 2013 at 6:40
  • post exception stack trace. Commented Jan 8, 2013 at 6:44
  • Are you posting JSON or an HTTP form? You set a Content-Type: header to application/json, but you set a RequestEntity that generates an entity appropriate for application/x-www-form-urlencoded. Commented Jan 8, 2013 at 6:50
  • You should post this string "valid JSON string cannot become a JSON object" Commented Jan 8, 2013 at 6:53

2 Answers 2

1

A string, eg, "Hello There" is not valid JSON. If you want to safeguard against this, you can always wrap your response with

responseString = "{ \"result\" : " + responseString + " }";

and then pass it to JSONObject and it will always parse correctly

Sign up to request clarification or add additional context in comments.

Comments

0
 JSONObject responseObject = new JSONObject(responseString);

Cannot convert to JSONObject exception is thrown if your input is not in JSON format. Check if responseString is a well formed JSON Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.