![](/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.