【发布时间】:2019-11-03 21:45:08
【问题描述】:
我需要在 android 中使用 retrofit2 从 JSON 生成 POJO,但问题是标签不时通过提供不同的查询。
JSON 1
{ "query":{
"pages":{
"4803":{
"pageid":4803,
"ns":0,
"title":"hello",
"extract":"Greating to some one"
}}}}
JSON 2
{ "query":{
"pages":{
"2354":{
"pageid":2354,
"ns":0,
"title":"Nice",
"extract":"Say Appreciation to someone"
}}}}
在上面的 2 个 JSON 值正在发生变化,例如 4803 和 2354 相似,我不知道高级所有值,所以如何生成 POJO 我尝试了很多在JSONtoPOJO 上,但它以 _4803 和 _2354 的名称创建类,但实际上通过向 API 提供不同的查询而改变了值。
这是我的所有 Java 代码 1.
public class Example {
@SerializedName("query")
@Expose
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
2.
public class modelClass {
@SerializedName("pageid")
@Expose
private Integer pageid;
@SerializedName("ns")
@Expose
private Integer ns;
@SerializedName("title")
@Expose
private String title;
@SerializedName("extract")
@Expose
private String extract;
public Integer getPageid() {
return pageid;
}
public void setPageid(Integer pageid) {
this.pageid = pageid;
}
public Integer getNs() {
return ns;
}
public void setNs(Integer ns) {
this.ns = ns;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getExtract() {
return extract;
}
public void setExtract(String extract) {
this.extract = extract;
}
}
3.
public class Pages {
@SerializedName("pages")
@Expose
private Map<String, modelClass> page;
public Map<String, modelClass> getPage() {
return page;
}
public void setPage(Map<String, modelClass> page) {
this.page = page;
}
}
5.
public class Query {
@SerializedName("pages")
@Expose
private Pages pages;
public Pages getPages() {
return pages;
}
public void setPages(Pages pages) {
this.pages = pages;
}
}
6.从 mainActivity 调用但返回 nullpointerException 那么如何提取值响应。
ApiService apiService = RetroClient.getApiService();
Call<Example> call = apiService.getWordList(//here i passed value, that return json//);
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
if (response.body() != null) {
// how get json value here
}
}
@Override
public void onFailure(Call<Example> call, Throwable t) {
}
});
请告诉我如何解决此类问题。谢谢。
【问题讨论】:
标签: android json retrofit2 pojo