从 Android 中的网页解析 JSON 不带括号

Parse JSON without Brackets from Webpage in Android

我需要从 https://realtimebitcoin.info/stats/ 获取 JSON 数据 (顺便说一句,link 可能会将您重定向到 https://realtimebitcoin.info/ or https://realtimebitcoin.info 如果发生这种情况,则只需在搜索框文本的末尾添加 stats/ 或 /stats/ 即可。

不幸的是,这份JSON文档的作者没有费心用括号括起来,甚至无法正确解析文档。我试图用“[]”强行包围它,但最后只创建了一个空对象,仍然无法解析。我的意思是 JSONException 不断被抛出。这是代码:

private static class UpdateBitcoinData extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {

        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {

            // URL url = new URL("https://api.myjson.com/bins/j5f6b");
            // URL url = new URL("https://api.myjson.com/bins/gfoa2");
            String data = "";
            URL url = new URL("https://realtimebitcoin.info/stats/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while (line != null) {
                line = bufferedReader.readLine();
                data = data + line;
            }
            String fixed = "[" + data + "]";
            JSONArray jsonArray = new JSONArray(fixed);
            for (int index = 0; index < jsonArray.length(); index++) {

                JSONObject jsonObject = (JSONObject) jsonArray.get(index);
                /* singleParsed =  "Name:" + JO.get("name") + "\n"+
                        "Password:" + JO.get("password") + "\n"+
                        "Contact:" + JO.get("contact") + "\n"+
                        "Country:" + JO.get("country") + "\n"; */
                BitcoinInformation.TEST = String.valueOf(jsonObject.get("ticker"));

            }

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (JSONException e) {

            e.printStackTrace();
            BitcoinInformation.TEST = e.getMessage();
        }

        return null;

    }

    @Override
    protected void onPostExecute(Void aVoid) {

        super.onPostExecute(aVoid);

    }

}

任何解决方案都会有所帮助!

JSON 此类端点很少(如果有的话)是手写的,它们通常通过某种对象的库转换为 JSON。

提供的 link 是一个 JSON 对象,具有 tickertotalbtchashrate.

属性

考虑到这一点,解析 JSON 的最简单方法是使用 JSONObject。

JSONObject jObject = new JSONObject( str );

其中 str 是包含 JSON 的字符串。查看更多关于如何使用 JSONObject here