簡體   English   中英

使用gson反序列化JSON對象數組時遇到問題

[英]Trouble deserializing an array of JSON objects using 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可以在以下位置看到:

查詢所有帖子

查詢一個帖子

當對信息進行序列化/反序列化時,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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM