解析json结果java

时间:2018-05-05 08:40:44

标签: java android json parsing

我在尝试解析json以获取theguardian新闻时遇到错误,并且说结果没有价值。我是一个noobie,我不确定我的代码的哪一部分是问题所在。每当我运行应用程序时,它都会正常运行,但不会在Feed中显示任何新闻

这是我的代码

public class NewsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {

    private static final String LOG_TAG = NewsActivity.class.getName();

    private static final String GUARDIAN_REQUEST_URL =
            "http://content.guardianapis.com/search?section=games&order-by=newest&api-key=test";

    private static final int NEWS_LOADER_ID = 1;

    private NewsAdapter mAdapter;

    private TextView mEmptyStateTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_activity);

        ListView newsListView = (ListView) findViewById(R.id.list);

        mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
        newsListView.setEmptyView(mEmptyStateTextView);

        mAdapter = new NewsAdapter(this, new ArrayList<News>());

        newsListView.setAdapter(mAdapter);

        newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                News currentNews = mAdapter.getItem(position);

                Uri newsUri = Uri.parse(currentNews.getUrl());

                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);

                startActivity(websiteIntent);
            }
        });

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getLoaderManager();

            loaderManager.initLoader(NEWS_LOADER_ID, null, this);
        } else {
            View loadingIndicator = findViewById(R.id.loading_indicator);
            loadingIndicator.setVisibility(View.GONE);

            mEmptyStateTextView.setText(R.string.no_internet_connection);
        }
    }

    @Override
    public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
        return new NewsLoader(this, GUARDIAN_REQUEST_URL);
    }

    @Override
    public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
        View loadingIndicator = findViewById(R.id.loading_indicator);
        loadingIndicator.setVisibility(View.GONE);

        mEmptyStateTextView.setText(R.string.no_news);

        if (news != null && !news.isEmpty()) {
            mAdapter.addAll(news);
            updateUi(news);
        }
    }

    private void updateUi(List<News> news) {
    }

    @Override
    public void onLoaderReset(Loader<List<News>> loader) {
        mAdapter.clear();
    }
}

QueryUtils

public class QueryUtils {

private static final String LOG_TAG = QueryUtils.class.getSimpleName();

private QueryUtils() {
}

public static List<News> fetchNewsData(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);
    }

    List<News> newss = extractResultFromJson(jsonResponse);

    return newss;
}

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;
}

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 news JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

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();
}

private static List<News> extractResultFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

    List<News> newss = new ArrayList<>();
    try {

        JSONObject baseJsonResponse = new JSONObject(newsJSON);

        JSONArray newsArray = baseJsonResponse.getJSONArray("results");

        for (int i = 0; i < newsArray.length(); i++) {

            JSONObject currentNews = newsArray.getJSONObject(i);

            String title =  currentNews.getString("webTitle");

            long date = currentNews.getLong("webPublicationDate");

            String url = currentNews.getString("webUrl");

            News news = new News(title, date, url);

            newss.add(news);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }

    return newss;
}

}

适配器

public class NewsAdapter extends ArrayAdapter<News> {

public NewsAdapter(Context context, List<News> news) {
    super(context, 0, news);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.news_list_item, parent, false);
    }

    News currentNews = getItem(position);

    TextView titleView = (TextView) listItemView.findViewById(R.id.title);
    String title = currentNews.getTitle();
    titleView.setText(title);

    TextView dateView = (TextView) listItemView.findViewById(R.id.date);
    String dateToString = String.valueOf(currentNews.getDate());
    String date = dateToString.substring(0, 10);
    dateView.setText(date);

    return listItemView;
}

} 清单

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".NewsActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

 错误消息

E/QueryUtils: Problem parsing the news JSON results
          org.json.JSONException: No value for results
              at org.json.JSONObject.get(JSONObject.java:392)
              at org.json.JSONObject.getJSONArray(JSONObject.java:587)
              at com.example.android.newsapp.QueryUtils.extractResultFromJson(QueryUtils.java:117)
              at com.example.android.newsapp.QueryUtils.fetchNewsData(QueryUtils.java:40)
              at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:30)
              at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:8)
              at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:315)
              at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
              at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:64)
              at android.os.AsyncTask$2.call(AsyncTask.java:333)
              at java.util.concurrent.FutureTask.run(FutureTask.java:266)
              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
              at java.lang.Thread.run(Thread.java:764)

感谢任何帮助或批评

2 个答案:

答案 0 :(得分:0)

首先你需要获得“响应”对象,然后才能在那里寻找“结果”数组

JSONObject baseJsonResponse = new JSONObject(newsJSON).getJSONObject(“response”);

JSONArray newsArray = baseJsonResponse.getJSONArray("results");

仔细看看你的json

答案 1 :(得分:0)

将extractResultFromJson方法替换为以下代码

private static List<News> extractResultFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

    List<News> newss = new ArrayList<>();
    try {

        JSONObject baseJsonResponse = new JSONObject(newsJSON);
        JSONObject mainResponse = baseJsonResponse.getJSONObject("response");

        JSONArray newsArray = mainResponse.getJSONArray("results");

        for (int i = 0; i < newsArray.length(); i++) {

            JSONObject currentNews = newsArray.getJSONObject(i);

            String title = currentNews.getString("webTitle");

            long date = currentNews.getLong("webPublicationDate");

            String url = currentNews.getString("webUrl");

            News news = new News(title, date, url);

            newss.add(news);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }

    return newss;
}

在获得Feed的结果后,请在适配器上调用notifyDataSetChange()