Как проанализировать данные WordPress REST API с помощью Retrofit и GSON? - PullRequest
0 голосов
/ 18 марта 2020

У меня есть этот тип JSON данных, и у меня есть проблема при разборе списка данных!

ЭТО МОЕ JSON ДАННЫЕ

[
    {
        "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
    }
]

Когда я анализирую сообщения, это дает мне Ожидаемый BEGIN_OBJECT, но был BEGIN_ARRAY в строке 1 пути 2 столбца $

Это мой файл, используемый для сериализации данных.

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;
    }
}

Кроме того, это мой файл, используемый для получения данных, таких как идентификатор, заголовок и т. Д. c ...

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;
    }
}

Последнее, что это мой класс модернизации.

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);
    }

}

Проблема в том, что я не могу разобрать тип данных, для списка нет имени

1 Ответ

1 голос
/ 09 апреля 2020

Это происходит потому, что тип данных, которые получает Gson, отличается от того, который вы указали. Я призываю вас использовать jsonschema2pojo

. Я поделюсь своим примером для извлечения данных из WordPress, затем я отобразил их в RecyclerView, надеюсь, это поможет.

Вы можете получить хорошее обзор по этой ссылке Модернизация

Класс RetroPost, который содержит поля, которые мне нужны из 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;
    }


}

Затем классы для объектов (например, заголовок и содержимое) в стороне содержание выше.

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;
    }

}

Затем интерфейс

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);


}

Наконец, способ загрузки данных

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) {



    }
});
...