2013-12-16 77 views
0

我從服務器端通過使用JSON一個PHP包裝返回的值。但是,當我將值返回給客戶端時發生以下錯誤。org.json.JSONException:java.lang.String類型的值數組不能轉換到的JSONObject

這是我的客戶端代碼

 @Override 
    protected Boolean doInBackground(String... arg0) { 

     try { 

      // Setup the parameters 
      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", 
        strNameToSearch)); 
      // Create the HTTP request 
      HttpParams httpParameters = new BasicHttpParams(); 

      // Setup timeouts 
      HttpConnectionParams 
        .setConnectionTimeout(httpParameters, 45000); 
      HttpConnectionParams.setSoTimeout(httpParameters, 45000); 

      HttpClient httpclient = new DefaultHttpClient(httpParameters); 
      HttpPost httppost = new HttpPost(
        "http://172.16.12.142/etsmobile/menuload.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 
      pasName = jsonObject.getString("Name"); 
      pasPost = jsonObject.getString("Post"); 
      pasStation = jsonObject.getString("Station"); 


     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

     return true; 
    } 

這是我的服務器端代碼

<?php 

$firstname = $_POST["FirstNameToSearch"]; 

$con = mysql_connect("localhost", "root", "") or die("Unable to connect to MySQL"); 


if (mysqli_connect_errno()) { 
    echo 'Database connection error: ' . mysqli_connect_error(); 
    exit(); 
} 

$selected = mysql_select_db("ets", $con) or die("Could not select ets"); 

$userdetails = mysql_query("SELECT users.* FROM login, users WHERE username = '$firstname' and login.emp_no=users.emp_no"); 
$getUser_result = mysql_fetch_assoc($userdetails); 


$name = $getUser_result['name']; 
$post = $getUser_result['post']; 
$station = $getUser_result['station']; 

mysql_close($con); 

$result_data = array('Name' => $name, 'Post' => $post, 'Station' => $station); 
//print_r($result_data); 
echo json_encode($result_data); 
?> 

這是我的JSON輸出

{"Name":"Sameera Yatawara","Post":"Station Master","Station":"Dematagoda"} 
+0

響應是一個字符串不是一個JSONObject – Raghunandan

+0

發佈你的JSON。 –

+0

@SotiriosDelimanolis我發佈了我的JSON。 – Dimi

回答

1

嘗試用這樣的檢索數據:

... 
String result = EntityUtils.toString(entity); 

JSONArray array = (JSONArray) new JSONTokener(result).nextValue(); 
JSONObject json = array.getJSONObject(0); 
json.getString('name'); 
... 

... 
String result = EntityUtils.toString(entity); 

JSONObject json = (JSONObject) new JSONTokener(result).nextValue(); 
json.getString('name'); 
... 

同時檢查PHP腳本編碼。我有類似的問題。我在文本編輯器(Notepad ++,..)中將編碼設置爲帶有DOM的UTF-8,並開始工作。

相關問題