英文:
Unable to retrieve value of 'totalResults' from JSON output
问题
这是我得到的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
。你可能想要检查一下以下几点:
- 确保
API_KEY
的值正确,因为你的URL中使用了它。 - 确保
xml
字符串中包含了预期的数据,可以通过在onPostExecute
方法中的Log.d("xml", xml);
来检查。 - 确保
Utils.loadProfiles(getBaseContext(), xml)
返回了非空的profileList
,并且Profile
对象的totalResults
属性被正确解析。
如果你已经确认了上述事项,但仍然遇到问题,你可能需要进一步检查代码以确保正确处理数据。
英文:
Here is JSON output I'm getting:
{
"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]"
}
]
}
Here's 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;
}
}
Here's the AsyncTask
for retrieving the data:
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");
}
}
}
Here's 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;
}
}
}
As you can see in the JSON output above, totalResults
is 38
but in the log in the AsyncTask class, it is showing D/PROGRESS_COUNT: 0
What am I doing wrong here?
答案1
得分: 2
Option - 1: 将您的代码更新,以在每个Profile
中包含totalResults
。请查看以下代码:
JSONObject jsonResponse = new JSONObject(xml);
JSONArray jsonArray = jsonResponse.optJSONArray("articles");
// 解析总结果
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);
// 将totalResults设置到每个profile中
profile.setTotalResults(totalResults);
profileList.add(profile);
}
return profileList;
Option - 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);
英文:
Option - 1: update your code to include totalResults
in each of Profile
. Check below:
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;
Option - 2: Update your model like below to match with your json
response and parse it.
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
}
And then parse your json
like below:
Article article = gson.fromJson(xml, Article.class);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论