我正在使用Volley Facebook库通过传递String参数来解析JSON对象。但它正在抛出JSON异常。
[
{
"error":false,
"newsletter":[
{
"title":"IPS Informa",
"date":"2015-12-02",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello World",
"id":"4",
"post_count":"0"
},
{
"title":"IPS Informa",
"date":"2015-11-30",
"posted_by":"admin",
"image":"1449324052220174144.png",
"description":"Hello Worl Two",
"id":"1",
"post_count":"6"
}
]
}
]
这是我的Android代码来解析我的JSON请求:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hidePDialog();
try {
JSONObject first = new JSONObject(response);
String err = first.getString("error");
JSONArray second = first.getJSONArray("newsletter");
fisco_tips.clear();
// Parsing json
for (int i = 0; i < second.length(); i++) {
JSONObject obj = second.getJSONObject(i);
FisoTipsSinglton fisco_obj = new FisoTipsSinglton();
//Set Newsletter ID
fisco_obj.setFisco_id(obj.getString("id"));
//Set Title
fisco_obj.setTitle(obj.getString("title"));
//Set Posted Date
fisco_obj.setPosted_date(obj.getString("date"));
//Set Posted By
fisco_obj.setPosted_by(obj.getString("posted_by"));
//Set Image URL
fisco_obj.setThumbnailUrl(obj.getString("image"));
//Set Short Description
fisco_obj.setShort_description(obj.getString("description"));
fisco_obj.setPost_count(obj.getString("post_count"));
fisco_tips.add(fisco_obj);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Json Error", "Here is error: " + e.toString());
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("country", country);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, related_posts);
}
如何在Android Volley库中使用字符串请求读取我的JSON对象?
答案 0 :(得分:1)
您收到的错误消息:
类型org.json.JSONArray无法转换为JSONObject
表示您正在尝试将JSONArray
转换为JSONObject
。这发生在try
块的第一行代码中。
JSONObject first = new JSONObject(response);
您将整个response
传递给JSONObject
构造函数,但响应包含在[ ]
中,因此它是JSONArray
,而不是JSONObject
}。您的第一步应该是将response
解析为JSONArray
,从数组的第一个元素中获取JSONObject
,然后继续解析。
try {
JSONArray wrapper = new JSONArray(response);
JSONObject first = (JSONObject)wrapper.get(0);
boolean err = first.getBoolean("error");
JSONArray newsletters = first.getJSONArray("newsletter");
// Parsing json
for (int i = 0; i < newsletters.length(); i++) {
JSONObject news = newsletters.getJSONObject(i);
.
.
.
}
} catch (JSONException e) {
Log.d("MainActivity.java", e.toString());
}
如果您的数据源有可能返回一个空数组,那么您应该执行比我在此处显示的更多错误检查。
答案 1 :(得分:0)
String err = first.getString("error");
应该是:
Boolean err = first.getBoolean("error");
再加上蜥蜴比尔说的话。
答案 2 :(得分:-1)
不使用Volley,而是使用Retrofit检查OkHTTP。它将自动包装响应;)