【发布时间】:2017-05-22 05:30:14
【问题描述】:
我正在开发 Android 应用程序,我需要从 Wordpress 博客(带有特定标签)获取帖子。 JSON API 插件已安装:https://wordpress.org/plugins/json-api/
在我的应用程序中,我使用 Volley 库。我收到此错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
我的代码:
String url = " http://christianconcepts.com/api/get_tag_posts/?tag_slug=appcontent ";
ListView postList;
List<Object> list;
Gson gson;
Map<String,Object> mapPost;
Map<String,Object> mapTitle;
String postTitle[];
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
gson = new Gson();
list = (List) gson.fromJson(s, List.class); // error line
postTitle = new String[list.size()];
for(int i=0;i<list.size();++i){
mapPost = (Map<String,Object>)list.get(i);
mapTitle = (Map<String, Object>) mapPost.get("title");
postTitle[i] = (String) mapTitle.get("rendered");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity().getApplicationContext(), "Some error occurred", Toast.LENGTH_LONG).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(myView.getContext());
rQueue.add(request);
有人可以帮助我并告诉我需要更改哪些内容才能使其正常工作吗?
【问题讨论】:
-
发布您的 JSON 响应
-
您显然有一个 json
object但正试图将其解析为 jsonarray。 -
你必须创建一个模型类。
-
发生异常是因为
fromJson方法需要List,因为您已经传递了List.class并且响应以JsonObject而不是List开头。所以首先你必须解析一个 JsonObject。
标签: android json android-studio android-volley json-api