[英]Using Volley to Parse an array from PHP into Android
我找不到有关从PHP将数组解析为我的android应用程序的任何资源。 我正在使用Volley处理连接。
目前,我在Web服务器上的PHP脚本中有一个数组,其中包含一个与数据库的连接,该数据库将来自MySQL查询的数据放入该数组中。
$latitude = array (
//Code for array here
);
$longitude = array (
//Code for array here
);
我能够连接到脚本,但无法弄清楚如何将PHP中的数组中的每个元素都获取到mainActivity.java文件中的数组中。
Java代码引发了一个异常,指出“纬度无值”。据我所知,这是因为“纬度”也尝试了“ $ latitude”,而不是数组名,而是变量名。 在PHP中,我认为没有这样的名字。
还有另一种方法可以将该数组的内容解析为Java。 我尝试过的Java代码是:
String url = "urlHere";
JSONObject jObj = new JSONObject();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, jObj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try
{
JSONArray jsonArray = response.getJSONArray("$latitude");
//Loop through array
for (int i = 0; i<jsonArray.length(); i++)
{
JSONObject locationItem = jsonArray.getJSONObject(i);
String latitude = locationItem.getString("index1");
}
}
catch (Exception e)
{
//Error encountered.
//Log Error
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Toast.makeText(getApplicationContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
});
所以出现错误的原因是
"latitude":
{
"index1": "100",
"index2": "200",
}
应该是( 为了使您的代码正常工作 ):
"latitude": [
{ "index1": "100" },
{ "index2": "200" },
]
index1
和index2
键的JSON对象。 index1
作为键在第一个元素中,而index2
在第二个元素中。 更新:
即使以上内容可以使您的代码正常工作 。 我建议您将JSON更改为:
"latitude": [
"100",
"200",
]
并为您的onResponse(...)
方法编写:
@Override
public void onResponse(JSONObject response) {
try
{
JSONArray jsonArray = response.getJSONArray("latitude");
//Loop through array
for (int i = 0; i<jsonArray.length(); i++)
{
String latitude = jsonArray.getString(i);
}
}
// Rest of your code can stay the same
}
对我来说似乎更直观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.