无法从JSON输出中获取“totalResults”的值。

huangapple go评论69阅读模式
英文:

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&amp;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输出中,totalResults38,但在AsyncTask类的日志中,它显示为 D/PROGRESS_COUNT: 0。你可能想要检查一下以下几点:

  1. 确保 API_KEY 的值正确,因为你的URL中使用了它。
  2. 确保 xml 字符串中包含了预期的数据,可以通过在 onPostExecute 方法中的 Log.d("xml", xml); 来检查。
  3. 确保 Utils.loadProfiles(getBaseContext(), xml) 返回了非空的 profileList,并且 Profile 对象的 totalResults 属性被正确解析。

如果你已经确认了上述事项,但仍然遇到问题,你可能需要进一步检查代码以确保正确处理数据。

英文:

Here is JSON output I'm getting:

{
  &quot;status&quot;: &quot;ok&quot;,
  &quot;totalResults&quot;: 38,
  &quot;articles&quot;: [
    {
      &quot;source&quot;: {
        &quot;id&quot;: null,
        &quot;name&quot;: &quot;Firstpost.com&quot;
      },
      &quot;author&quot;: null,
      &quot;title&quot;: &quot;Astronaut with blood clot on ISS gets successfully treated by doctor on Earth - Firstpost&quot;,
      &quot;description&quot;: &quot;The ISS had a limited supply of blood thinners that they had to make do with till the next re-supply mission.&quot;,
      &quot;url&quot;: &quot;https://www.firstpost.com/tech/science/astronaut-with-blood-clot-on-iss-gets-successfully-treated-by-doctor-on-earth-7866961.html&quot;,
      &quot;urlToImage&quot;: &quot;https://images.firstpost.com/wp-content/uploads/2018/08/ISS_NASA.jpg&quot;,
      &quot;publishedAt&quot;: &quot;2020-01-06T10:24:12Z&quot;,
      &quot;content&quot;: &quot;tech2 News StaffJan 06, 2020 15:54:12 IST\r\nHow on Earth does someone treat a life-threatening blood clot when you&#39;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]&quot;
    }
  ]
}

Here's Profile.java:

public class Profile {

    @SerializedName(&quot;urlToImage&quot;)
    @Expose
    private String imageUrl;

    @SerializedName(&quot;title&quot;)
    @Expose
    private String title;

    @SerializedName(&quot;totalResults&quot;)
    @Expose
    private int totalResults;

    @SerializedName(&quot;url&quot;)
    @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&lt;String, Void, String&gt; {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        protected String doInBackground(String... args) {
            String xml = &quot;&quot;;

            String urlParameters = &quot;&quot;;
            xml = Function.excuteGet(&quot;https://newsapi.org/v2/top-headlines?country=in&amp;apiKey=&quot;+API_KEY, urlParameters);
            return xml;
        }
        @Override
        protected void onPostExecute(final String xml) {

            if (xml != null) {
                if (xml.length() &gt; 10) { // Just checking if not empty

                    Log.d(&quot;xml&quot;, xml);

                    for (final Profile profile : Utils.loadProfiles(getBaseContext(), xml)) {
                        PROGRESS_COUNT = profile.getTotalResults();
                        Log.d(&quot;PROGRESS_COUNT&quot;, String.valueOf(PROGRESS_COUNT));
                        storiesProgressView.setStoriesCount(PROGRESS_COUNT);
                        storiesProgressView.setStoryDuration(3000L);
                        storiesProgressView.startStories();
                    }

                } else {
                    Toast.makeText(getApplicationContext(), &quot;No news found&quot;, Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.d(&quot;xml&quot;, &quot;Null&quot;);
            }
        }

    }

Here's Utils.java:

public class Utils {

    private static final String TAG = &quot;Utils&quot;;

    public static List&lt;Profile&gt; loadProfiles(Context context, String xml) {

        try {
            JSONObject jsonResponse = new JSONObject(xml);
            JSONArray jsonArray = jsonResponse.optJSONArray(&quot;articles&quot;);
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            List&lt;Profile&gt; profileList = new ArrayList&lt;&gt;();

            for (int i = 0; i &lt; 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(&quot;articles&quot;);

// parse the total result
int totalResults = jsonResponse.optInt(&quot;totalResults&quot;);

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
List&lt;Profile&gt; profileList = new ArrayList&lt;&gt;();

for (int i = 0; i &lt; 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(&quot;status&quot;)
    @Expose
    private String status;

    @SerializedName(&quot;totalResults&quot;)
    @Expose
    private int totalResults;

    @SerializedName(&quot;articles&quot;)
    @Expose
    private List&lt;Profile&gt; articles;

    // getter-setter
}

Profile.java:

public class Profile {

    @SerializedName(&quot;urlToImage&quot;)
    @Expose
    private String imageUrl;

    @SerializedName(&quot;title&quot;)
    @Expose
    private String title;

    @SerializedName(&quot;url&quot;)
    @Expose
    private String url;

    // getter-setter
}

And then parse your json like below:

Article article = gson.fromJson(xml, Article.class);

huangapple
  • 本文由 发表于 2020年1月6日 21:00:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定