嗨,我有这段代码:
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 Chow Resstaurant”
只需要对此进行一些指导
答案 0 :(得分:0)
因为你必须用库Gson,Jackson等解析Json,或者你也可以手动解析它
手动方式:http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
Gson:https://sites.google.com/site/gson/gson-user-guide
杰克逊:http://wiki.fasterxml.com/JacksonInFiveMinutes
我建议使用 Gson