0

我正在编写一个 android 阅读器应用程序,该应用程序使用 wordpress REST API 从 wordpress.com 站点提取内容,该应用程序返回 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 可以在以下位置看到:

查询所有帖子

查询一个帖子

4

1 回答 1

1

GSON 在序列化/反序列化信息时支持“强”和“弱”类型的概念。强类型表示具有良好定义接口的实际 Java bean 对象。弱类型表示数据(键/值)对的映射。目前您正在尝试混合和匹配两种模型,但这是行不通的。您要求 GSON 将您的数据反序列化为“强”类型 ( PostsHandler)。但是在该类中,您正在存储 GSON 的“弱”类型(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();
}
于 2013-02-25T04:50:41.030 回答