这是我得到的JSON输出:
{
"status": "ok",
"totalResults": 38,
"articles": [
{
"source": {
"id": null,
"name": "Firstpost.com"
},
"author": null,
"title": "Astronaut with blood clot on ISS gets successfully treated by doctor on Earth - Firstpost",
"description": "The ISS had a limited supply of blood thinners that they had to make do with till the next re-supply mission.",
"url": "https://www.firstpost.com/tech/science/astronaut-with-blood-clot-on-iss-gets-successfully-treated-by-doctor-on-earth-7866961.html",
"urlToImage": "https://images.firstpost.com/wp-content/uploads/2018/08/ISS_NASA.jpg",
"publishedAt": "2020-01-06T10:24:12Z",
"content": "tech2 News StaffJan 06, 2020 15:54:12 IST\r\nHow on Earth does someone treat a life-threatening blood clot when you're in space? Dr Stephan Moll at the University of North Carolina School of Medicine a doctor and clotting expert can tell you how.\r\nIn an unprece… [+3928 chars]"
}
]
}
这里是Profile.java
:
public class Profile {
@SerializedName("urlToImage")
@Expose
private String imageUrl;
@SerializedName("title")
@Expose
private String title;
@SerializedName("totalResults")
@Expose
private int totalResults;
@SerializedName("url")
@Expose
private String url;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTotalResults() {
return totalResults;
}
public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
这里是用于检索数据的AsyncTask
:
class DownloadNews extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String xml = "";
String urlParameters = "";
xml = Function.excuteGet("https://newsapi.org/v2/top-headlines?country=in&apiKey="+API_KEY, urlParameters);
return xml;
}
@Override
protected void onPostExecute(final String xml) {
if (xml != null) {
if (xml.length() > 10) { // Just checking if not empty
Log.d("xml", xml);
for (final Profile profile : Utils.loadProfiles(getBaseContext(), xml)) {
PROGRESS_COUNT = profile.getTotalResults();
Log.d("PROGRESS_COUNT", String.valueOf(PROGRESS_COUNT));
storiesProgressView.setStoriesCount(PROGRESS_COUNT);
storiesProgressView.setStoryDuration(3000L);
storiesProgressView.startStories();
}
} else {
Toast.makeText(getApplicationContext(), "No news found", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("xml", "Null");
}
}
}
这里是Utils.java
:
public class Utils {
private static final String TAG = "Utils";
public static List<Profile> loadProfiles(Context context, String xml) {
try {
JSONObject jsonResponse = new JSONObject(xml);
JSONArray jsonArray = jsonResponse.optJSONArray("articles");
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
List<Profile> profileList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Profile profile = gson.fromJson(jsonArray.getString(i), Profile.class);
profileList.add(profile);
}
return profileList;
} catch (JSONException e) {
Toast.makeText(context.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
}
您可以在上面的JSON输出中看到,totalResults
是38
,但是在AsyncTask类的日志中,它显示的是D/PROGRESS_COUNT: 0
我在这里做错了什么?
Option-1:更新您的代码以将totalResults
包含在每个Profile
中。检查以下:
JSONObject jsonResponse = new JSONObject(xml);
JSONArray jsonArray = jsonResponse.optJSONArray("articles");
// parse the total result
int totalResults = jsonResponse.optInt("totalResults");
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
List<Profile> profileList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Profile profile = gson.fromJson(jsonArray.getString(i), Profile.class);
// set totalResults to each profile
profile.setTotalResults(totalResults);
profileList.add(profile);
}
return profileList;
选项-2:如下更新模型以与json
响应相匹配:
Article.java:
public class Article {
@SerializedName("status")
@Expose
private String status;
@SerializedName("totalResults")
@Expose
private int totalResults;
@SerializedName("articles")
@Expose
private List<Profile> articles;
// getter-setter
}
Profile.java:
public class Profile {
@SerializedName("urlToImage")
@Expose
private String imageUrl;
@SerializedName("title")
@Expose
private String title;
@SerializedName("url")
@Expose
private String url;
// getter-setter
}
然后像下面一样解析您的json
:
Article article = gson.fromJson(xml, Article.class);