我正在開發一個android應用程序,它使用sql & php連接到外部服務器。我能夠將正確的信息檢索到應用程序中,但是,我無法處理解析的JSON數據。Android:操縱解析JSON爲IF聲明
此代碼成功返回我查詢的數據。
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","venID: "+json_data.getInt("venID")
);
//Get an output to the screen
returnString += jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
我確認,我想返回的數據是正確的把它變成一個TextView:
final TextView txt = (TextView)findViewById(R.id.textView2);
txt.setText(getServerData(KEY_121));
,並顯示結果爲:
http://xxx.xxx.x.xxx/sponsorimage.php{"venID":"1"}
我想知道如何我可能會操縱返回的信息,讓結果只顯示數字1,因爲我正在嘗試取該字符串並在if語句中使用它來執行另一個操作
編輯
下面是該特定部分
public static final String KEY_121 = "http://xxx.xxx.x.xxx/sponsorimage.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sponsorImage","0"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//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","venID: "+json_data.getInt("venID")
);
//Get an output to the screen
returnString += jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
的任何參數我下面,我給出的例子。最終,我需要將許多事情連接到單個字符串。 我的問題是,我該如何操作返回的信息http://xxx.xxx.x.xxx/sponsorimage.php{"venID":"1「}才能顯示1? – thedoubleu 2011-12-22 08:35:13
你可以使用split(「\」「)[3]來獲得這個數字,但它是脆弱和醜陋的黑客。更好的解決方案是實現正確解析JSON對象,或者只是提取適當的值而不是連接所有內容廚房水槽 – 2011-12-22 08:43:06
我已經嘗試了「\」拆分,並且這是不成功的,你會建議如何正確解析JSON對象,我可以看到的任何提示或區域都可以在php腳本或android文件 – thedoubleu 2011-12-22 08:52:05