我正在使用Volley Facebook庫通過傳遞字符串參數來解析JSON對象。但它引發了JSON異常。如何使用Volley解析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的凌空庫的字符串要求我讀我的JSON對象?
在你的問題中的迴應是一個數組,而不是一個對象。但我不確定這是否是您的問題,因爲您沒有發佈錯誤消息。 –
@Billthelizard錯誤消息是 類型org.json.JSONArray無法轉換爲JSONObject – Bilal
那是您的(第一個)問題。你將響應當作一個對象來處理,但它是一個包含對象的數組。首先將對象從陣列中取出。 –