![](/img/trans.png)
[英]How to get Json array name json_encode from php array? Android
[英]How to get php json_encode($array) in to android to manipulate it data?
如何獲取php json_encode($array)
到Android來操縱它的數據?
我有一個在json_encode($ array)中編碼數組的php; 當我
echo json_encode($array);
我得到:
[{"id":"1","name":"player1","score":"20","quarter":"Q - 1"},{"id":"2","name":"player2","score":"18","quarter":"http:\\/\\/localhost\\/win.jpg"}]
現在在android中,我想從php獲取該數組並將其放入一個數組,該數組讓我以索引名為例,該索引包含它包含的字符串值,然后從索引0中獲取,然后將該字符串設置為textView文本。 在iPhone中,我只執行以下代碼:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(數據是我的本地網址“ http://localhost/my.php”)
然后我可以輕松地從字典中使用valueForKey:name
和objectAtIndex:0
提取數據,並將其字符串放入文本字段。
請完成Java中的代碼實現,以便我理解。 因為我是Java的新手,所以我以大量錯誤和嘗試以不同方式進行操作的時間迷失了方向。
感謝解決我的問題的人。
使用org.apache.http.client.HttpClient接收對字符串的響應。
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(this.getURL());
// attach the request with post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username", username));
pairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
//send request to server
HttpResponse response = httpclient.execute(httppost);
//trace response
InputStream is = response.getEntity().getContent();
//convert response to string
BufferedReader myReader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(myReader.readLine() + "\n");
String line="";
while ((line = myReader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
然后,您可以使用org.json.JSONObject或org.json.JSONArray。
JSONObject json_data= new JSONObject(result);
int userId = Integer.parseInt(json_data.getString("user_id"));
JSONArray arrJson = json_data.getJSONArray("data");
有許多第三方類別可自動完成大部分工作。 我們不需要發明輪子。 輕松使用Retrofit或Volley。 在我的項目中工作得很好。 他們代表您照顧許多事情。 定義一個類以將每個玩家對象的所有屬性打包到一個sigle對象中,然后使用改造API:也許以下提示將對您有所幫助:
public interface QuestionAPI {
@GET("player.php")//you can call php file directly
public void getFeed(Callback <List<PlayerObject>> playerobject);
}
發生此錯誤是因為您發送的json數組沒有名稱。
存儲json數組后,請執行以下操作:
echo json_encode(array('acdata'=>$acdata));
eg:
while($row = $stmt->fetch ()){
$acdata[] = array(
'acid' => $acid,
'address' => $address,
'companyname' => $companyname,
'dateofpurchase' => $dateofpurchase,
'ac_type' => $ac_type
);
}
header('Content-type: application/json');
echo json_encode(array('acdata'=>$acdata));
然后在android中通過以下方式檢索它:
JSONObject jsonRootObject = new JSONObject(result);
JSONArray jsonArray = jsonRootObject.optJSONArray("acdata");
JSONObject jsonObject = jsonArray.getJSONObject(1);
name = jsonObject.optString("acid");
// acid是json中鍵的名稱
//將其循環以獲取所有值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.