提取JSON响应数据时出现问题

时间:2018-07-26 19:42:04

标签: java json

我正在尝试为该课程构建应用程序,该课程将从特定的JSON中提取新闻数据并显示在屏幕上。我记录了我的错误,但它拒绝了我提取数据的方式。这是json布局的示例:

"response": {
"status": "ok",
"userTier": "developer",
"total": 2050598,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 205060,
"orderBy": "newest",
"results": [
  {
    "id": "technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
    "type": "article",
    "sectionId": "technology",
    "sectionName": "Technology",
    "webPublicationDate": "2018-07-26T19:12:07Z",
    "webTitle": "Does Facebook's plummeting stock spell disaster for the social network?",
    "webUrl": "https:\/\/www.theguardian.com\/technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
    "apiUrl": "https:\/\/content.guardianapis.com\/technology\/2018\/jul\/26\/facebook-stock-price-falling-what-does-it-mean-analysis",
    "isHosted": false,
    "pillarId": "pillar\/news",
    "pillarName": "News"
  },

这是我不喜欢的结果代码:

// Returns News List from JSON Response
private static List<News> extractFeatureFromJson(String newsJSON) {
    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

    // Create an empty ArrayList that we can add news stories to
    List<News> news = new ArrayList<>();

    // Try to parse the JSON response string. Errors will be sent to log.
    try {

        // Create a JSONObject from the JSON response string
        JSONObject baseJsonResponse = new JSONObject(newsJSON);

        // Extract the JSONArray associated with the key called "response",
        JSONArray newsArray = baseJsonResponse.getJSONArray("response");

        // For each article in the newsArray, create an {@link News} object
        for (int i = 0; i < newsArray.length(); i++) {

            // Get a single article at position i within the list of articles
            JSONObject currentNews = newsArray.getJSONObject(i);

            // Extract results for news story
            JSONObject results = currentNews.getJSONObject("results");

            // Extract the value for the key called webTitle
            String webTitle = results.getString("webTitle");

            // Extract the value for the key called "sectionName"
            String sectionName = results.getString("sectionName");

            // Extract the value for the key called "webPublicationDate"
            long webPublicationDate = results.getLong("webPublicationDate");

            // Extract the value for the key called "webUrl"
            String webUrl = results.getString("webUrl");

            // Create a new {@link Earthquake} object with the title, category, date,
            // and url from the JSON response.
            News news1 = new News(webTitle, sectionName, webPublicationDate, webUrl);

            // Add the new {@link News} to the list of articles.
            news.add(news1);
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing the Guardian JSON results", e);
    }

    // Return the list of articles
    return news;
}

我不明白我到底在做什么错,因为我觉得自己正在复制数据,对吗?无论如何,我不知道。

这也使我的装载机出错:

public class NewsLoader extends AsyncTaskLoader<List<News>> {

// Tag for Log Messages
private static final String LOG_TAG = NewsLoader.class.getName();

// Query URL
private String mUrl;

/**
 * Constructs a new {@link NewsLoader}.
 * @param context of the activity
 * @param url to load data from
 */
public NewsLoader(Context context, String url) {
    super(context);
    mUrl = url;
}

@Override
protected void onStartLoading() {
    forceLoad();
}

@Override
//Background Thread
public List<News> loadInBackground() {
    if (mUrl == null) {
        return null;
    }

    // Perform the network request, parse the response, and extract news articles.
    List<News> news = QueryUtils.fetchNewsData(mUrl);
    return news;
} }

引发的错误:

        at com.example.android.newsapp.QueryUtils.extractFeatureFromJson(QueryUtils.java:135)
    at com.example.android.newsapp.QueryUtils.fetchNewsData(QueryUtils.java:44)
    at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:42)
    at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:11)

1 个答案:

答案 0 :(得分:0)

1)“响应”是JSON对象,而不是JSON数组。

2)“结果”是JSON数组,而不是JSON对象。

3)webPublicationDate类型为Sting,不是长。

为了正确解析Json,请尝试以下操作:

// Returns News List from JSON Response

private static List<News> extractFeatureFromJson(String newsJSON) {
    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

// Create an empty ArrayList that we can add news stories to
List<News> news = new ArrayList<>();

// Try to parse the JSON response string. Errors will be sent to log.
try {

    // Create a JSONObject from the JSON response string
    JSONObject baseJsonResponse = new JSONObject(newsJSON);

    // Extract the JSONArray associated with the key called "response",
    JSONObject resultObject = baseJsonResponse.getJSONObject("response");

    // Extract JSON array of resultObject
    JSONArray newsArray = resultObject.getJSONArray("results");

    // For each article in the resultObject, create an {@link News} object
    for (int i = 0; i < newsArray.length(); i++) {

        // Get a single article at position i within the list of articles
        JSONObject currentNews = newsArray.getJSONObject(i); 

        // Extract the value for the key called webTitle
        String webTitle = currentNews.getString("webTitle");

        // Extract the value for the key called "sectionName"
        String sectionName = currentNews.getString("sectionName");

        // Extract the value for the key called "webPublicationDate"
        String webPublicationDate = currentNews.getString("webPublicationDate");

        // Extract the value for the key called "webUrl"
        String webUrl = currentNews.getString("webUrl");

        // Create a new {@link Earthquake} object with the title, category, date,
        // and url from the JSON response.
        // CHANGE YOUR NEWS CLASS' webPublicationDate FIELD TO STRING OR 
        // DON'T FORGET TO CONVERT IT TO LONG!!!!
        News news1 = new News(webTitle, sectionName, webPublicationDate, webUrl);

        // Add the new {@link News} to the list of articles.
        news.add(news1);
    }

} catch (JSONException e) {
    // If an error is thrown when executing any of the above statements in the "try" block,
    // catch the exception here, so the app doesn't crash. Print a log message
    // with the message from the exception.
    Log.e("QueryUtils", "Problem parsing the Guardian JSON results", e);
}

// Return the list of articles
return news;

}

希望我能为您服务! 最好的祝福, Csongor