我可以使我的数据的编码json不是这个
的格式{"tbl_accepted":[{"renterLat":"15.706376","renterLng":"121.065852"}]}
我只想得到Lat和Lng的值,所以我可以相应地在单独的textViews中显示它们。这就是我如何得到它。
private void getJSON(String url){
class GetJSON extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params){
String uri = params[0];
BufferedReader bufferedReader = null;
try{
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json=bufferedReader.readLine()) != null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
@Override
protected void onPostExecute(String s){
super.onPostExecute(s);
tvLat.setText(s);
Log.d(TAG,tvLat.getText().toString());
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
<?php
include_once("connection.php");
$where = '';
if (isset($_GET['renter'])){
$where = " WHERE renter like '%".addslashes($_GET['renter'])."%'";
}
$sql = "SELECT renterLat, renterLng FROM tbl_accepted ".$where." ORDER BY acceptedID DESC";
$result = mysqli_query($conn, $sql);
$json = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$json['tbl_accepted'][]=$row;
}
}
mysqli_close($conn);
echo json_encode($json);
?>
先谢谢先生。
答案 0 :(得分:0)
您在onPostExecute
中收到了关注字符串。
{"tbl_accepted":[{"renterLat":"15.706376","renterLng":"121.065852"}]}
使用JSONObject
和JSONArray
将 JSON字符串转换为对象。
要将字符串转换为对象,您可以在onPostExecute
中看起来像这样。
@Override
protected void onPostExecute(String s){
super.onPostExecute(s);
JSONObject latObj=new JSONObject(s);
JSONArray tbl_accepted=latObj.getJSONArray('tbl_accepted');
tvLat.setText(tbl_accepted.getJSONObject(0).getString('renterLat'));
Log.d(TAG,tvLat.getText().toString());
}