Php Android中json.GetJSONArray(“?”)的问题
我正在努力让我的代码工作。我想建立一个mysql连接 并将带有json的数据发送到我的android应用程序。 我想它几乎可以工作,但我的logcat在最后几乎给了我这个警告: 分析数据值[{staff_phone:123,staff_name:fabian等]时出错。 我猜我的sql脚本中有错误。以下是脚本:Php Android中json.GetJSONArray(“?”)的问题,php,android,mysql,json,arrays,Php,Android,Mysql,Json,Arrays,我正在努力让我的代码工作。我想建立一个mysql连接 并将带有json的数据发送到我的android应用程序。 我想它几乎可以工作,但我的logcat在最后几乎给了我这个警告: 分析数据值[{staff_phone:123,staff_name:fabian等]时出错。 我猜我的sql脚本中有错误。以下是脚本: mysql_connect($db_host,$db_user,$db_pwd); mysql_select_db($database); $result = mysql_query("
mysql_connect($db_host,$db_user,$db_pwd);
mysql_select_db($database);
$result = mysql_query("SELECT * FROM contactlijst");
$array = array();
while ($row = mysql_fetch_assoc($result))
{
array_push($array, $row);
}
print json_encode($array);
mysql_close();
以下是我的java代码:
还有这个:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json =
Database.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try{
JSONArray contactinfo = json.getJSONArray("contactlijst");
//Loop the Array
for(int i=0;i < contactinfo.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
那么我做错了什么?
非常感谢!getJSONArray希望获得一个值为数组的键。因此它希望JSON看起来更像这样:
{contactlijst:[{员工电话:123,员工姓名:fabian
如果这不起作用,请尝试验证您的JSON以确保其格式正确。我经常使用它
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json =
Database.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try{
JSONArray contactinfo = json.getJSONArray("contactlijst");
//Loop the Array
for(int i=0;i < contactinfo.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}