2011-12-25 56 views
0

您好我有這樣的代碼片段:Android的轉換JSON字符串

protected void onPostExecute(String response) { 
      String res=response.toString(); 
      // res = res.trim(); 
      res= res.replaceAll("\\s+",""); 
      if(!res.equals("0")){ 
       un.setVisibility(View.GONE); 
       ok.setVisibility(View.GONE); 
       error.setVisibility(View.GONE); 
       key.setVisibility(View.GONE); 
       merchant.setVisibility(View.VISIBLE); 
       String data = getServerData(res); 
       merchant.setText(data); 
      } 
      else 
       error.setText("Incorrect Password"); 

     } 


    } 
    private String getServerData(String returnString) { 

      InputStream is = null; 

      String result = ""; 




      //convert response to string 
      try{ 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 
        while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
        } 
        is.close(); 
        result=sb.toString(); 
      }catch(Exception e){ 
        Log.e("log_tag", "Error converting result "+e.toString()); 
      } 
      //parse json data 
      try{ 
        JSONArray jArray = new JSONArray(result); 
        for(int i=0;i<jArray.length();i++){ 
          JSONObject json_data = jArray.getJSONObject(i); 
          Log.i("log_tag","merchant_id: "+json_data.getInt("merchant_id")+ 
            ", merchant_name: "+json_data.getString("merchant_name") 
          ); 
          //Get an output to the screen 
          returnString += "\n\t" + jArray.getJSONObject(i); 
        } 
      }catch(JSONException e){ 
        Log.e("log_tag", "Error parsing data "+e.toString()); 
      } 
      return returnString; 
     } 

這PHP代碼:

include 'config.php'; 
include 'opendb.php'; 
$key = $_POST['username']; 
$key = mysql_real_escape_string($key); 

$sql = "SELECT merchant_id, merchant_name FROM merchants WHERE merchant_key = '$key'"; 
$number = mysql_query($sql); 
$rows = mysql_num_rows($number); 

if ($rows > 0){ 
    while($result=mysql_fetch_assoc($number)){ 
     $output[]=$result; 
     print(json_encode($result)); 
    } 
} 
else{ 
    echo 0; 
} 

基本上Android模擬器屏幕我得到的JSON陣列:

{"merchant_id":"1", 
"merchant_name": 
"ChowRestaurant"} 

我想以這種方式在屏幕上顯示:

「1周Resstaurant」

只需要在這個

回答