Volley for Android的JSONArray响应 [英] JSONArray response with Volley for Android
问题描述
我正在使用Volley将一些数据发布到数据库中,并且得到以下jsonarray响应.
I am posting some data into the database using Volley and I get the following jsonarray response.
[
{
"nickname":"panikos",
"username":"panikos@gmail.com",
"user_type":"LEADER",
"latest_steps":"0"
}
]
这是我的代码示例,很遗憾,它没有注销或调试昵称"对象的变量:(.
This is a sample of my code that unfortunately doesn't log out or debug the variable of "nickname" object:(.
final JsonArrayRequest jsonObjReq1 = new
JsonArrayRequest(AppConfig.URL_GET_TEAM, jsonObject,
new com.android.volley.Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
有什么想法吗?我想念什么吗?
Any ideas? Am I missing something?
谢谢.
推荐答案
我的问题可能是-您已经将response
作为JSONArray
了.
I the problem might be - you are already getting response
as a JSONArray
.
因此,您可以致电
JSONObject jresponse = response.getJSONObject(0);
如果响应中有多个对象,则
and if you have more than 1 object in response, then
for(int i = 0; i < response.length(); i++){
JSONObject jresponse = response.getJSONObject(i);
String nickname = jresponse.getString("nickname");
Log.d("nickname", nickname);
}
删除此内容:
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
并添加:
try {
JSONObject jresponse = response.getJSONObject(0);
String nickname = jresponse.getString("nickname");
Log.d("nickname",nickname);
}catch (JSONException e) {
e.printStackTrace();
}
代码看起来不错,但是我认为您可能错过了在请求队列中添加jsonObjReq1
的调用.我建议使用单人模式.
The Code looks good, however i think you might be missing a call to add jsonObjReq1
in the request queue. I would suggest to use Singleton Pattern.
这篇关于Volley for Android的JSONArray响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!