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


php server parse simple string using JSON to Android client

嗨,我在Android客户端php服务器中很新。我遵循了一些教程的帖子和响应变量JSON但这个响应错误Value of type java.lang.String cannot be converted to JSONObject .

JSON帖子是成功的,但响应是错误的。

安卓代码:

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);  

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

用这个替换你的代码可能会起作用。从服务器获取响应作为对象而不是字符串。

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