JSON提取作者Guardian API



所以,我正在尝试从《卫报》上提取JSON。

基本上,我可以得到除了至关重要的作者以外的所有内容。

如何或什么是提取此方法的方法。

非常感谢我对所有这一切的新手,并且已经问了过去的问题,没有任何建议将不胜感激。

queryutils.java

    package com.example.android.newsapp;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class QueryUtils {
    private static final String TAG = QueryUtils.class.getSimpleName();
    public static Context context;
    private QueryUtils() {
    }
    public static List<News> fetchNews(String requestUrl) {
        URL url = createUrl(requestUrl);
        String json_response = null;
        try {
            json_response = makeHttpRequest(url);
            Log.i(TAG, json_response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<News> news = extractFromJson(json_response);
        return news;
    }
    private static URL createUrl(String StringUrl) {
        URL url = null;
        try {
            url = new URL(StringUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return url;
    }
    private static String makeHttpRequest(URL url) throws IOException {
        String json_response = "";
        if (url == null) {
            return json_response;
        }
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        try {
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setConnectTimeout(15000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                inputStream = httpURLConnection.getInputStream();
                json_response = readFromString(inputStream);
            } else {
                Log.e(TAG, "Error" + httpURLConnection.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return json_response;
    }
    private static String readFromString(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    } private static String extractString(JSONObject newInfo, String stringName) {
        String str = null;
        try {
            str = newInfo.getString(stringName);
        } catch (JSONException e) {
            Log.e(TAG, context.getString(R.string.query_util_error_extract_string) + stringName);
        }
        if (str != null) {
            return str;
        } else {
            return context.getString(R.string.empty_string);
        }
    }
    private static List<News> extractFromJson(String news_json) {
        if (TextUtils.isEmpty(news_json)) {
            return null;
        }
        List<News> news = new ArrayList<News>();
        try {
            JSONObject baseJson = new JSONObject(news_json);
            JSONArray news_array = baseJson.getJSONObject("response").getJSONArray("results");
            for (int i = 0; i < news_array.length(); i++) {
                JSONObject currentNews = news_array.getJSONObject(i);
                String name = currentNews.getString("sectionName");
                String title = currentNews.getString("webTitle");
                String date = currentNews.getString("webPublicationDate");
                String url = currentNews.getString("webUrl");
                JSONArray tags = baseJson.getJSONArray("tags");

                String contributor = null;
                if (tags.length() == 1) {
                    JSONObject contributorTag = (JSONObject) tags.get(0);

                    contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));
                } else {
                    //no contributor
                    contributor = context.getString(R.string.empty_string);
                }
                    News mNews = new News(name, title, date, url, contributor);
                news.add(mNews);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return news;
    }
}

这是我从中提取的JSON。 https://content.guardianapis.com/search?q=debate&Amp; tag=politics/politics&amp; from-date = 2014-01-01-01-01&amp-emp.App-key = test

这是数据管理器.. http://open-platform.theguardian.com/documentation/

我也很难获得作者。我做出了两个更改解决了问题。

首先,我确实必须更改添加&amp; show-tags = rul.

的贡献者。

第二,我不得不在解析中调整您的IF语句才能阅读。而不是:

contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));

我替换为:

contributor = contributorTag.getString("webTitle");

(键" webtitle"包含作者的名字(

您使用的一个问题是您使用的URL不会给出包含Webtitle键的标签阵列,即使我使用&amp; amp; show-tags =贡献者进行了调整。

我使用的URL是:http://content.guardianapis.com/search?&;

完整的queryutils.java文件是:

package com.example.android.technewsapps1;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public final class QueryUtils {
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();
    private QueryUtils() {
    }
    /**
     * Query the Guardian dataset and return a list of NewsStory objects.
     */
    public static List<NewsStory> fetchNewsStoryData(String requestUrl) {
        // Create URL object
        URL url = createUrl(requestUrl);
        // Perform HTTP request to the URL and receive a JSON response back
        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem making the HTTP request.", e);
        }
        // Extract relevant fields from the JSON response and create a list of NewsStories
        List<NewsStory> newsStories = extractFeatureFromJson(jsonResponse);
        // Return the list of NewsStories
        return newsStories;
    }

    /**
     * Returns new URL object from the given String URL.
     */
    private static URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Problem building the URL ", e);
        }
        return url;
    }
    /**
     * Make an HTTP request to the given URL and return a String as the response.
     */
    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        // If the URL is null, then return early.
        if (url == null) {
            return jsonResponse;
        }
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            // If the request was successful (response code 200),
            // then read the input stream and parse the response.
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the newsStory JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // Closing the input stream could throw an IOException, which is why
                // the makeHttpRequest(URL url) method signature specifies than an IOException
                // could be thrown.
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    /**
     * Convert the {@link InputStream} into a String which contains the
     * whole JSON response from the server.
     */
    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();

    }
    /**
     * Return a list of NewsStory objects that has been built up from
     * parsing the given JSON response.
     */
    private static List<NewsStory> extractFeatureFromJson(String newsStoryJSON) {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(newsStoryJSON)) {
            return null;
        }
        // Create an empty ArrayList that we can start adding news stories to
        List<NewsStory> newsStories = new ArrayList<>();
        // Try to parse the JSON response string. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {
            // Create a JSONObject from the JSON response string
            JSONObject baseJsonResponse = new JSONObject(newsStoryJSON);
            //Create the JSONObject with the key "response"
            JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
            //JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
            // Extract the JSONArray associated with the key called "results",
            // which represents a list of news stories.
            JSONArray newsStoryArray = responseJSONObject.getJSONArray("results");
            // For each newsStory in the newsStoryArray, create an NewsStory object
            for (int i = 0; i < newsStoryArray.length(); i++) {
                // Get a single newsStory at position i within the list of news stories
                JSONObject currentStory = newsStoryArray.getJSONObject(i);
                // Extract the value for the key called "webTitle"
                String title = currentStory.getString("webTitle");
                // Extract the value for the key called "sectionName"
                String sectionName = currentStory.getString("sectionName");
                // Extract the value for the key called "webPublicationDate"
                String date = currentStory.getString("webPublicationDate");
                // Extract the value for the key called "url"
                String url = currentStory.getString("webUrl");
                //Extract the JSONArray with the key "tag"
                JSONArray tagsArray = currentStory.getJSONArray("tags");
                //Declare String variable to hold author name
                String authorName = null;
                if (tagsArray.length() == 1) {
                    JSONObject contributorTag = (JSONObject) tagsArray.get(0);
                    authorName = contributorTag.getString("webTitle");
                }
                // Create a new NewsStory object with the title, section name, date,
                // and url from the JSON response.
                NewsStory newsStory = new NewsStory(title, sectionName, date, url, authorName);
                // Add the new NewsStory to the list of newsStories.
                newsStories.add(newsStory);
            }
        } 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 newsStory JSON results", e);
        }
        // Return the list of earthquakes
        return newsStories;
    }

}

相关内容

  • 没有找到相关文章

最新更新