java.lang.String无法转换为JSONObject

时间:2014-12-05 07:43:19

标签: java android json android-json

@Override
protected JSONObject doInBackground(String... params) {

    String path = null;
    String response = null;
    HashMap<String, String> request = null;
    JSONObject requestJson = null;
    DefaultHttpClient httpClient = null;
    HttpPost httpPost = null;
    StringEntity requestString = null;
    ResponseHandler<String> responseHandler = null;

    // get the username and password
    Log.i("Email", params[0]);
    Log.i("Password", params[1]);

    try {

        path = "http://192.xxx.x.xxx/xxxxService/UsersService.svc/UserAuthentication";
        new URL(path);
    } catch (MalformedURLException e) {

        e.printStackTrace();
    }

    try {

        // set the API request
        request = new HashMap<String, String>();
        request.put(new String("Email"), params[0]);
        request.put(new String("Password"), params[1]);
        request.entrySet().iterator();

        // Store locations in JSON
        requestJson = new JSONObject(request);
        httpClient = new DefaultHttpClient();
        httpPost = new HttpPost(path);
        requestString = new StringEntity(requestJson.toString());

        // sets the post request as the resulting string
        httpPost.setEntity(requestString);
        httpPost.setHeader("Content-type", "application/json");

        // Handles the response
        responseHandler = new BasicResponseHandler();
        response = httpClient.execute(httpPost, responseHandler);

        responseJson = new JSONObject(response);


    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        responseJson = new JSONObject(response);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return responseJson;
}

我正在使用此代码登录我的应用。

responseJson = new JSONObject(response);

我对响应有“成功”,但responseJson值为“null”

这就是我得到的:

Error converting result org.json.JSONException: Value Fail of type java.lang.String cannot be converted to JSONObject
如果我能得到一个礼貌,我会很好 提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
 // your logic
}else if(json instanceof JSONObject){
//your logic
}