首页 > 解决方案 > 在 Android Recyclerview 中解析 JSON 对象流

问题描述

我正在尝试解析一个附有 JSON 对象列表的 URL,如下所示:

    {
       "to":{
          "id":"X/4w7pz9L48=",
          "name":"Willie Hart"
       },
       "from":{
          "id":"YziKGGTsckQ=",
          "name":"Andy Stafford"
       },
       "timestamp":"1633376913009",
       "areFriends":true
    }{
       "to":{
          "id":"xRstXf+DJKw=",
          "name":"Clarence Hansen"
       },
       "from":{
          "id":"JUVS3wLLBPA=",
          "name":"Terry Russell"
       },
       "timestamp":"1633376913018",
       "areFriends":true
    }{

它不是有效的 JSON 格式,但我试图将其解析为我的 Android 应用程序中的 recyclerview,但无法仅解析我在此文件中看到的 JSONObjects。这是我必须解析数据的示例:

    public class JSONTask extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... strings) {
            String current = "";

            try
            {
                URL url;
                HttpURLConnection urlConnection = null;
                try {
                    url = new URL("https://codechallenge.secrethouse.party/?since=[timestamp_in_seconds]");
                    urlConnection = (HttpURLConnection) url.openConnection();

                    InputStream in = urlConnection.getErrorStream();
                    InputStreamReader isw = new InputStreamReader(in);

                    int data = isw.read();

                    while(data != -1)
                    {
                        current += (char) data;
                        data = isw.read();
                    }

                    return current;
                } catch(Exception e)
                {
                    e.printStackTrace();
                } finally {
                    if(urlConnection != null)
                    {
                        urlConnection.disconnect();
                    }
                }
            } catch(Exception e)
            {
                e.printStackTrace();
                return "Exception: " + e.getMessage();
            }
            return current;
        }

        @Override
        protected void onPostExecute(String s) {
            try {

                JSONObject obj = new JSONObject(s);

                //parse the 'To" object
                JSONObject toNameObject = obj.getJSONObject("to");
                toNameList.add(toNameObject.getString("name"));

                //parse the 'From' object
                JSONObject fromNameObject = obj.getJSONObject("from");
                fromNameList.add(fromNameObject.getString("name"));

                //parse the 'Timestamp' object
                timeStampList.add(obj.getString("timestamp"));
            } catch(JSONException e) {
                e.printStackTrace();
            }
        }

我从运行这个得到的错误是:org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

我的问题是,这个链接指向一大堆 JSONObjects,是否可以只解析这些对象?或者链接是否需要指向具有正确结构的有效 JSON 文件?

标签: androidjsonandroid-recyclerview

解决方案


推荐阅读