如何让php json_encode($array)
进入Android来操纵它的数据?
我有一个 php,它用 json_encode($array) 编码数组;当我
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");
发生此错误是因为您发送的 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));
然后在安卓中通过以下方式检索它:
JSONObject jsonRootObject = new JSONObject(result);
JSONArray jsonArray = jsonRootObject.optJSONArray("acdata");
JSONObject jsonObject = jsonArray.getJSONObject(1);
name = jsonObject.optString("acid");
酸是 JSON 中键的名称
将其放在循环中以获取所有值
有许多第三方类可以自动完成大部分作业。我们不需要发明轮子。轻松使用改装或凌空抽射。在我的项目中工作得很好。他们代表您处理许多事情。定义一个类以将每个玩家对象的所有属性打包到 sigle 对象中,然后使用改造 API:也许以下提示会对您有所帮助:
public interface QuestionAPI {
@GET("player.php")//you can call php file directly
public void getFeed(Callback <List<PlayerObject>> playerobject);
}