php服务器解析使用JSON到Android客户端的简单字符串

时间:2014-11-25 05:53:30

标签: php android json

您好,我是Android客户端php服务器中的新手。我按照JSON关注帖子和响应变量的一些教程,但这个响应错误Value of type java.lang.String cannot be converted to JSONObject

JSON帖子成功但响应错误。

Android代码:

HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);           

HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.1/databastest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));        
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

String result = EntityUtils.toString(entity);

// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);

//Retrieve the data from the JSON object
resultLoging = jsonObject.getString("ResultArray");


}catch (Exception e){
    Log.e("ClientServerDemo", "Error:", e);
    exception = e;
}

return true;
}

@Override
protected void onPostExecute(Boolean valid){
    //Update the UI
    Toast.makeText(mContext, resultLoging, Toast.LENGTH_LONG).show();
    if(exception != null){
        Log.i("Error",exception.getMessage());
        Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

php代码

mysqli_query($con,"INSERT INTO usersacc
(phone, password) VALUES('$pho', '$pass')");


        #Build the result array (Assign keys to the values) 
        $result_data = array( 
           'ResultArray' => 'success',
            ); 

        #Output the JSON data 
        echo json_encode($result_data);  

插入成功,但结果未完成。

1 个答案:

答案 0 :(得分:0)

将此代码替换为可能有用的代码。从服务器获取响应,而不是字符串。

Object result = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(result.toString()); 
resultLoging = jsonObject.getString("ResultArray");