How to parse data of WordPress REST API using Retrofit and GSON?

99封情书 提交于 2021-01-07 03:45:39

问题


i have this type of JSON data and i have a problem on parsing list of data!

THIS IS MY JSON DATA

[
    {
        "id": 17502,
        "link": "https://www.angrybirds.com/blog/get-ready-angry-birds-movie-2-premiere-new-game-events/",
        "title": {
            "rendered": "Get ready for The Angry Birds Movie 2 premiere with new in-game events!"
        },
        "excerpt": {
            "rendered": "<p>The Angry Birds Movie 2 comes to US theaters tomorrow, but who wants to wait that long?! Good news: you can get into the movie mood right now with a new batch of Angry Birds Movie 2 events in your favorite Angry Birds games! Prime the hype engine with the trailer for The Angry Birds [&hellip;]</p>\n",
            "protected": false
        },
        "author": 3
    },
    {
        "id": 17447,
        "link": "https://www.angrybirds.com/blog/angry-birds-ar-isle-pigs-available-now/",
        "title": {
            "rendered": "Angry Birds AR: Isle of Pigs is available now!"
        },
        "excerpt": {
            "rendered": "<p>Classic Angry Birds gameplay + AR = an incredible amount of fun! Play Angry Birds AR: Isle of Pigs now on your ARKit enabled iOS device.</p>\n",
            "protected": false
        },
        "author": 3
    }
]

When i parse posts it gives me Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

This is my file used to serialize data.

public class WordPressMain {
    private List<WordPressData> data;

    public WordPressMain(List<WordPressData> data) {
        this.data = data;
    }

    public List<WordPressData> getData() {
        return data;
    }

    public void setData(List<WordPressData> data) {
        this.data = data;
    }
}

Also this is my file used to get data like id, title, etc...

public class WordPressData {
    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("date")
    @Expose
    private String date;

    @SerializedName("title")
    @Expose
    private WordPressTitle title;

    public WordPressData() {
    }

    public WordPressData(int id, String date, WordPressTitle title) {
        this.id = id;
        this.date = date;
        this.title = title;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public WordPressTitle getTitle() {
        return title;
    }

    public void setTitle(WordPressTitle title) {
        this.title = title;
    }
}

Last thing this is my Retrofit Class.

public class WordPressApi {

    // Parse Url Using Parameters
    public static final String BASE_URL = "https://www.angrybirds.com/";
    private static Posts posts = null;

    public static Posts getMainVideo() {
        if (posts == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            posts = retrofit.create(Posts.class);
        }
        return posts;
    }


    public interface Posts {
        @GET
        Call<WordPressMain> getWordPress(@Url String url);
    }

}

The Problem Is I Can't Parse Type Of Data, There Is No Name For The List


回答1:


This happen because the type of data Gson is receiving is different than what you identified. I encourage you using jsonschema2pojo

I will share my example to retrieve data from WordPress, then I displayed them in a RecyclerView I hope it helps.

You may get good overview from this link Retrofit

RetroPost Class which contains the fields I need from Wordpress.

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;


public class RetroPost {

    @SerializedName("id")
    @Expose
    private Integer id;

    @SerializedName("date_gmt")
    @Expose
    private String dateGmt;

    @SerializedName("status")
    @Expose
    private String status;

    @SerializedName("link")
    @Expose
    private String link;

    @SerializedName("title")
    @Expose
    private RetroPostTitle title;

    @SerializedName("content")
    @Expose
    private RetroPostContent content;

    @SerializedName("author")
    @Expose
    private Integer author;

    @SerializedName("comment_status")
    @Expose
    private String commentStatus;

    @SerializedName("categories")
    @Expose
    private List<Integer> categories = null;

    @SerializedName("city")
    @Expose
    private List<Integer> city = null;

    @SerializedName("jetpack_featured_media_url")
    @Expose
    private String jetpackFeaturedMediaUrl;



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDateGmt() {
        return dateGmt;
    }

    public void setDateGmt(String dateGmt) {
        this.dateGmt = dateGmt;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public RetroPostTitle getTitle() {
        return title;
    }

    public void setTitle(RetroPostTitle title) {
        this.title = title;
    }

    public RetroPostContent getContent() {
        return content;
    }

    public void setContent(RetroPostContent content) {
        this.content = content;
    }

    public Integer getAuthor() {
        return author;
    }

    public void setAuthor(Integer author) {
        this.author = author;
    }

    public String getCommentStatus() {
        return commentStatus;
    }

    public void setCommentStatus(String commentStatus) {
        this.commentStatus = commentStatus;
    }

    public List<Integer> getCategories() {
        return categories;
    }

    public void setCategories(List<Integer> categories) {
        this.categories = categories;
    }

    public List<Integer> getCity() {
        return city;
    }

    public void setCity(List<Integer> city) {
        this.city = city;
    }

    public String getJetpackFeaturedMediaUrl() {
        return jetpackFeaturedMediaUrl;
    }

    public void setJetpackFeaturedMediaUrl(String jetpackFeaturedMediaUrl) {
        this.jetpackFeaturedMediaUrl = jetpackFeaturedMediaUrl;
    }


}

Then the Classes for Objects (like title & content) in side above content.

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class RetroPostTitle {

    @SerializedName("rendered")
    @Expose
    private String rendered;

    public String getRendered() {
        return rendered;
    }

    public void setRendered(String rendered) {
        this.rendered = rendered;
    }

}

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class RetroPostContent {

    @SerializedName("rendered")
    @Expose
    private String rendered;
    @SerializedName("protected")
    @Expose
    private Boolean _protected;

    public String getRendered() {
        return rendered;
    }

    public void setRendered(String rendered) {
        this.rendered = rendered;
    }

    public Boolean getProtected() {
        return _protected;
    }

    public void setProtected(Boolean _protected) {
        this._protected = _protected;
    }

}

Then the interface

import java.io.File;
import java.util.List;

import retrofit2.http.GET;
import retrofit2.http.Query;

public interface WordPressApi {

    @GET("/wp-json/wp/v2/posts/")
    Call<List<RetroPost>> getPosts(@Query("per_page") String strPerPage);


}

Finally, the method to load the data

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(MyGlobalVars.strURL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

WordPressApi wordPressApi = retrofit.create(WordPressApi.class);

postsCall = wordPressApi.getPosts("50");

postsCall.enqueue(new Callback<List<RetroPost>>() {
    @Override
    public void onResponse(Call<List<RetroPost>> call, Response<List<RetroPost>> response) {

        if (!response.isSuccessful()) {
           AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setMessage("Something wrong, contact admin")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //do things
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();

            return;
        }

        ArrayList<HomePostItems> postsList = new ArrayList<>();
        List<RetroPost> retroPosts = response.body();
        for (RetroPost retroPostItem : retroPosts) {
            int intID = retroPostItem.getId();
            String strTitle = retroPostItem.getTitle().getRendered();
            String strFeaturedImage = retroPostItem.getJetpackFeaturedMediaUrl();
            String strDate = retroPostItem.getDateGmt();
            String strAuthor = retroPostItem.getAuthor().toString();
            String strCity = "102";
            String strCategory = "100";
            String strLink = retroPostItem.getLink();
            postsList.add(new HomePostItems(strFeaturedImage, strTitle, strDate, strCity,
                    intID, strLink));
        }

        mRecyclerView = getView().findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getContext());
        mAdapter = new HomePostsAdapter(postsList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    public void onFailure(Call<List<RetroPost>> call, Throwable t) {



    }
});


来源:https://stackoverflow.com/questions/60746596/how-to-parse-data-of-wordpress-rest-api-using-retrofit-and-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!