簡體   English   中英

如何獲取json數組的子節點的值

[英]How to get the value of a child node of a json array

請我在解析此鏈接( https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23 )的數據列表時遇到一些問題,我能夠從json數組(文章)中獲取數據但是我怎樣才能從 josn 數組中獲取數據(來源)

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

這是我用來獲取文章數據的代碼。 獲取我嘗試過的來源

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

但我想我沒有正確獲取代碼

這是我嘗試過的第二個選項

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

但這只會給我空文本字段填充數據的空間但它是空白的請任何幫助將不勝感激

我不知道你的代碼是如何工作的。 您試圖將JSONObject作為文章獲取,實際上是JSONArray 除此之外,我在你的json沒有找到任何,比如source而是我找到了source 要解析嘗試以下方式:

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

正如 Md. Asaduzzaman 所說,它實際上是一個 JSON 數組(確切地說是“文章”)。

我已經在我的手機上測試過它,它沒有問題。 您將不得不嘗試弄清楚您希望如何解析 JSONArray。

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

    }

}

在這里,您將找到JSON所需的一切。

祝你好運:)

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

希望能幫到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM