如何使用 Retrofit 和 GSON 解析 WordPress REST API 的数据?
How to parse data of WordPress REST API using Retrofit and GSON?
我有这种类型的 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 […]</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;
}
}
这也是我用来获取 ID、标题等数据的文件...
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;
}
}
最后一件事是我的改装 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);
}
}
问题是我无法解析数据类型,列表没有名称
发生这种情况是因为 Gson 接收的数据类型与您识别的不同。我鼓励您使用 jsonschema2pojo
我将分享我的示例以从 WordPress 检索数据,然后我将它们显示在 RecyclerView 中希望它有所帮助。
您可能会从中得到很好的概述 link Retrofit
RetroPost Class 其中包含我需要的 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;
}
}
然后 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;
}
}
然后是界面
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) {
}
});
我有这种类型的 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 […]</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;
}
}
这也是我用来获取 ID、标题等数据的文件...
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;
}
}
最后一件事是我的改装 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);
}
}
问题是我无法解析数据类型,列表没有名称
发生这种情况是因为 Gson 接收的数据类型与您识别的不同。我鼓励您使用 jsonschema2pojo
我将分享我的示例以从 WordPress 检索数据,然后我将它们显示在 RecyclerView 中希望它有所帮助。
您可能会从中得到很好的概述 link Retrofit
RetroPost Class 其中包含我需要的 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;
}
}
然后 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;
}
}
然后是界面
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) {
}
});