[英]how to parse json data in android
如何在Android中讀取PHP文件發送的Json數據
這是PHP代碼
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
echo $data_string;
這是讀取數據的代碼android json
InputStream instream = entity.getContent();
// String result = "";
Log.i("--------etat---------r","-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-");
String result = this.convertStreamToString(instream);
Log.i("--------etat---------r","-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-");
這是分析InputStream對象的方法
public String convertStreamToString(InputStream is) {
convertStreamToString " );
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
但是這是顯示的代碼
11-15 10:46:58.744: I/Read from server(526): Call Stack 11-15 10:46:58.744: I/Read from server(526): #TimeMemoryFunctionLocation 11-15 10:46:58.744: I/Read from server(526): 10.0006142200{main}( )..\\younesservices.php : 0 11-15 10:46:58.744: I/Read from server(526): 11-15 10:46:58.744: I/Read from server(526): {"name":"Hagrid","age":"36"} 11-15 10:46:58.744:I /從服務器(526)讀取:11-15 10:46:58.744:I /從服務器(526)讀取:(!)SCREAM:11-15 10的錯誤抑制被忽略: 46:58.744:I /從服務器讀取(526):(!)注意:未定義的索引:C:\\ wamp \\ www \\ younes_project \\ younesservices.php在第行11-15 10:46:58.744:json從服務器(526):調用堆棧11-15 10:46:58.744:I /從服務器(526)讀取:#TimeMemoryFunctionLocation 11-15 10:46:58.744:I /從服務器(526)讀取:10.0006142200 {main} (.. \\ younesservices.php : 0 11-15 10:46:58.744:I /從服務器讀取(526):11-15 10:46:58.744:I /從服務器讀取(526): {“名稱” :“ Hagrid”,“ age”:“ 36”}
但我只讀變量
這: {“名稱”:“ Hagrid”,“年齡”:“ 36”}
使用此代碼。
public String getResult(String url){
Log.v(TAG, "Final Requsting URL is : :"+url);
String line = "";
String responseData = null;
try {
StringBuilder sb = new StringBuilder();
String x = "";
URL httpurl = new URL(url);
URLConnection tc= httpurl.openConnection();
/*URLConnection tc = twitter.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) tc;
httpConnection.setRequestMethod("POST");*/
//tc.setRe
//tc.setDoOutput(false);
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
x = sb.toString();
}
responseData = new String(x);
}
catch (FileNotFoundException e) {
Log.v("NewWebHelper", "FileNotFoundException :");
e.printStackTrace();
}
catch (IOException e) {
Log.v("NewWebHelper", "IOException :");
e.printStackTrace();
}
catch (Exception e) {
Log.v("NewWebHelper", "Exception :");
e.printStackTrace();
}
return responseData;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.