简体   繁体   中英

How to get the value of a child node of a json array

please i am having some issues parsing a list of data form the this link( https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23 ) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)

    private void getWebApiData() {
        String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
        new AsyncHttpTask.execute(WebDataUrl);
    }

    @SuppressLint("StaticFieldLeak")
    public class AsyncHttpTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            String result = "";

            URL url;
            HttpsURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpsURLConnection) url.openConnection();
                if (result != null) {
                    String response = streamToString(urlConnection.getInputStream());
                    parseResult(response);
                    return result;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                newsAdapter = new NewsAdapter(getActivity(), newsClassList);
                listView.setAdapter(newsAdapter);
                Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
            }
            progressBar.setVisibility(View.GONE);
        }
    }

    private String streamToString(InputStream stream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        String line;
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

        // Close stream
        if (null != stream) {
            stream.close();
        }
        return result;
    }


    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONObject response2 = response.getJSONObject("articles");
            NewsClass newsClass;
            for (int i = 0; i < newsClass.length(); i++) {
                JSONObject post = newsClass.optJSONObject(i);
                String name = post.optString("name");
                newsClass = new newsClass();
                newsClass.setNews_Name(name);
                artistClassList.add(newsClass);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

This is code I am using the get the data of the articles. To get the sources I have tried

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONObject response2 = response.getJSONArray("articles");
            JSONObject response3 = response2.getJSONObject("sources");
            NewsClass newsClass;
            for (int i = 0; i < newsClass.length(); i++) {
                JSONObject post = newsClass.optJSONObject(i);
                String name = post.optString("name");
                newsClass = new newsClass();
                newsClass.setNews_Name(name);
                artistClassList.add(newsClass);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

But I think I am not getting the code correctly

Here is the second option I have tried

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);

            JSONObject response = response2.getJSONObject("sources");
            NewsClass newsClass;
            for (int i = 0; i < newsClass.length(); i++) {
                JSONObject post = newsClass.optJSONObject(i);
                String name = post.optString("name");
                newsClass = new newsClass();
                newsClass.setNews_Name(name);
                artistClassList.add(newsClass);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

But this only gives me empty text Fields the spaces for the data is populated but it is blank Please any help will be greatly appreciated

I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray . Besides this I don't find any key in your json like sources instead I have found source . To parse source try below way:

try {
    JSONObject jsonObject = new JSONObject(result);
    JSONArray jsonArray = jsonObject.getJSONArray("articles");

    for(int i = 0; i < jsonArray.length(); i++) {
        JSONObject articleObject = jsonArray.getJSONObject(i);
        JSONObject sourceObject = articleObject.getJSONObject("source");

        String name = sourceObject.optString("name");
        String url = sourceObject.optString("url");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).

I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.

private class AsyncTaskExample extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {

    }
    @Override
    protected String doInBackground(String... strings) {
        try {
            stringURL = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();

            //render string stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            String line;
            String result = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }

            // Close stream
            if (null != is) {
                is.close();
            }

            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    protected void onPostExecute(String js) {
        super.onPostExecute(js);
        try {
            JSONObject  jay = new JSONObject (js);
            JSONObject source = jay.getJSONObject("articles");

            String s = source.getString("title");
            System.out.println(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Here you will find all you need for JSON .

Best of luck to you :)

JSONObject jsonObject = new JSONObject(response.body().string());
            JSONArray articles = jsonObject.getJSONArray("articles");
            for(int i=0; i<articles.length(); i++){
                JSONObject obj1 = (JSONObject) articles.get(i);
                JSONObject source = obj1.getJSONObject("source");
                Log.i(TAG, "onResponse: " + source.toString()); }

Hope that help you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM