【发布时间】:2018-04-05 00:35:45
【问题描述】:
到目前为止,我必须像这样使用 array-data-name 在 php 中创建 json:
print "{data : ".json_encode($the_data,JSON_UNESCAPED_UNICODE)."}"
在 java 的 android studio 中我喜欢这样:
String url = "httpmywebsite";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i ) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String email = respons.getString("email");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
它工作正常,但现在我想更新我的 php 文件
来自:
print "{data : ".json_encode($the_data,JSON_UNESCAPED_UNICODE)."}"
到;
print json_encode($the_data,JSON_UNESCAPED_UNICODE)
所以我尝试像下面那样更新我的 volley 的 java 代码,但不起作用!
JSONArray jsonArray= new JSONArray(response.toString());
新的 php 代码返回这个 json:
[{"0":"100","id":"100","1":"sandra","name":"sandra","2":"x@x.com","email":"x@x.com"}]
我已添加此代码来获取 volley 的错误类型;
@Override
public void onErrorResponse(VolleyError 错误) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.error_network_timeout),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
Toast.makeText(context,
"ParseError",
Toast.LENGTH_LONG).show();
}
}
我收到这条消息:ParseError
【问题讨论】:
-
请包含所有新代码,而不是一行。
-
其余的保持不变,我刚刚替换了这一行:
JSONArray jsonArray = jsonObject.getJSONArray("data");与这一行:JSONArray jsonArray= new JSONArray(response.toString()); -
嗯,我看不出它为什么不起作用。 “不起作用”是什么意思?您是否测试过您的 php 页面是否返回了正确的数据?它到底在代码中的哪个点崩溃?讯息是什么?请更新问题。
-
是的,我检查了 php json 结果。我得到这个结果:
[{"0":"100","id":"100","1":"sandra","name":"sandra","2":"x@x.com","email":"x@x.com"}] -
它会崩溃吗?你是什么意思“不起作用”。
标签: java json android-volley