无法使用gson反序列化JSON对象数组

时间:2013-02-25 04:30:17

标签: java android json wordpress gson

我正在编写一个Android阅读器应用程序,它使用wordpress REST API从wordpress.com网站提取内容,该API将我反序列化的JSON对象返回到应用程序中定义的Article对象。以下代码可以正确地获取单个帖子的数据:

    private class getOne extends AsyncTask <Void, Void, JSONObject> {
    private static final String url = "https://public-api.wordpress.com/rest/v1/sites/drewmore4.wordpress.com/posts/slug:good-one";
    @Override
    protected JSONObject doInBackground(Void... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");

        HttpResponse response;
        JSONObject object = new JSONObject();
        String resprint = new String();

        try {
            response = httpclient.execute(httpget);
            // Get the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // get entity contents and convert it to string
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                resprint = result;
                // construct a JSON object with result
                object=new JSONObject(result);
                // Closing the input stream will trigger connection release
                instream.close();
            }
        } 
        catch (ClientProtocolException e) {System.out.println("CPE"); e.printStackTrace();} 
        catch (IOException e) {System.out.println("IOE"); e.printStackTrace();} 
        catch (JSONException e) { System.out.println("JSONe"); e.printStackTrace();}

        return object;
    }
    @Override
    protected void onPostExecute (JSONObject object){
        System.out.println("POSTStexxx");
        Gson gson = new Gson();


        Article a = gson.fromJson(object.toString(), Article.class);
        System.out.println("XXCONTENT: " + a.content);

        System.out.println(a.ID);
        System.out.println(a.title);
        System.out.println(a.author.name);
    //  System.out.println(a.attachments.URL);

        WebView wv = (WebView)findViewById(R.id.mainview);

        wv.loadDataWithBaseURL(url, a.content, "text/html", "UTF-8", null);
        wv.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);


    }

}

println语句显示预期结果,确认对象已正确反序列化。以下代码应该从网站上的所有帖子获取数据,但无法正常运行:

private class getAll extends AsyncTask <Void, Void, JSONObject> {
    private static final String url = "https://public-api.wordpress.com/rest/v1/sites/drewmore4.wordpress.com/posts/";
    @Override
    protected JSONObject doInBackground(Void... params) {

         //set up client and prepare request object to accept a json object
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");
        JSONObject returned = new JSONObject();
        HttpResponse response;

        String resprint = new String();

        try {
            response = httpclient.execute(httpget);
            // Get the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // get entity contents and convert it to string
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                resprint = result;
                // construct a JSON object with result
                returned =new JSONObject(result);
                // Closing the input stream will trigger connection release
                instream.close();
            }
        } 
        catch (ClientProtocolException e) {System.out.println("CPE"); e.printStackTrace();} 
        catch (IOException e) {System.out.println("IOE"); e.printStackTrace();} 
        catch (JSONException e) { System.out.println("JSONe"); e.printStackTrace();}

       // stories = object;
        return returned;
    }

    @Override
    protected void onPostExecute (JSONObject returned){
        System.out.println("POSTStexxx");
        Gson gson = new Gson();

        PostsHandler ph = gson.fromJson(returned.toString(), PostsHandler.class);

        System.out.println("WAKAWAKA: " +  ph.posts.length);

    //  System.out.println("ARRAYLENGTH" + ja.length());
        ArrayList<Article> arts = new ArrayList<Article>();

        for (JSONObject o : ph.posts) {
            Article a = gson.fromJson(o.toString(), Article.class);
            System.out.println("TITLE: " + a.title);
                            System.out.println("TITLE: " + a.author);
            arts.add(a);
        }
        System.out.println("ARTICLEARRAY: " + arts.size());
        stories = arts;
        populateUI();

    }

此处返回的JSON对象包含一个JSONArray对象,与对单个帖子的查询返回的对象相同。该程序运行,这里的println语句之一显示arraylist的大小是正确的(即匹配预期的帖子数),但每个对象(标题,作者等)的字段为空。我猜我没有正确对待阵列,但我不知道我在哪里犯错。这是Article类,它映射每个post对象:

public class Article implements Serializable {

//  private static final long serialVersionUID = 1L;
    int ID;
    public String title;
    public String excerpt;
    public Author author;
    public String date;     
    public String URL;

    @SerializedName("featured_image")
    public String image;        
    public String content;
    //public String[] attachments;

    public Attachment attachments;
    public int comment_count;
    public int like_count;


}   


class Author {
long id;
String name;
String URL;
}

PostsHandler类,映射了对所有帖子的查询的响应(我怀疑我的问题在哪里):

public class PostsHandler {
    int number;
JSONObject[] posts;

}

所有未标记@SerializedName注释的字段都与JSONObjects中使用的字段相同。

我正在使用的JSONObjects可以在以下位置看到:

query for all posts

query for one post

1 个答案:

答案 0 :(得分:1)

GSON支持“强大”的概念。并且“弱”&#39;在序列化/反序列化信息时键入。强类型表示具有良好定义的接口的实际Java bean对象。弱类型表示数据(键/值)对的映射。目前,您正在尝试混合和匹配两种模型,但这些模型都不起作用。您要求GSON将您的数据反序列化为强大的数据。输入(PostsHandler)。但是在那个课程中,你正在存储GSON的弱点&#39;类型(JSONObjects)。你应该选择(并坚持)一个处理模型。我们假设我们将使用强类型来反序列化数据。

这就是我实现PostsHandler

的方法
public PostsHandler implements Serializable {
    @SerializedName("found")
    private int number;

    @SerializedName("posts")
    private List<Article> articles

    // Constructors, getters, setters
}

onPostExecute

@Override
protected void onPostExecute (JSONObject returned) {
    Gson gson = new Gson();
    PostsHandler ph = gson.fromJson(returned.toString(), PostsHandler.class);

    System.out.println("Article array length: " + ph.getArticles().size());
    stories = arts;
    populateUI();
}
相关问题