【问题标题】:Cannot retrieve complete json response in Android logcat and Gives error or parsing无法在 Android logcat 中检索完整的 json 响应并给出错误或解析
【发布时间】:2017-01-22 13:42:03
【问题描述】:

我正在开发一个应用程序并发出一个运行良好的 http 请求,

这是我的异步类 Doinbackground 方法:

@Override
    protected String doInBackground(Void... arg0) {


        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.d("Response ==>", "Response from url: ");
        longInfo(jsonStr);
        return jsonStr; 
    }

这是我正在使用的逻辑

        public void longInfo(String str) {
        if(str.length() > 4000) {
            Log.e("TAG", str.substring(0, 4000));
            longInfo(str.substring(4000));
        } else
            Log.e("TAG", str);
    }

但这给了我大量的 json 字符串,它破坏了 json 格式,我无法相应地解析对象和数组。请帮忙

这里是我的json解析方法

 public void parsejsonp(String jsonp){


        if (jsonp != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonp);
                int count = jsonObj.getInt("count");
                Log.e("count=> ",count+"");

                int count_total = jsonObj.getInt("count_total");
                Log.e("count_total=> ",count_total+"");

                int pages = jsonObj.getInt("pages");
                Log.e("pages=> ",pages+"");


                // Getting JSON Array node
                JSONArray Posts = jsonObj.getJSONArray("posts");

                // looping through All Posts
                for (int i = 0; i < Posts.length(); i++) {
                    JSONObject c = Posts.getJSONObject(i);

                    String id = c.getString("id");
                    String type = c.getString("type");
                    String slug = c.getString("slug");
                    String status = c.getString("status");
                    String title = c.getString("title");

                    String title_plain = c.getString("title_plain");

                    String content = c.getString("content");

                    String date = c.getString("date");

                    String modified = c.getString("modified");




                    // Phone node is JSON Object
                    //                     JSONObject phone = c.getJSONObject("phone");
                    //                   String mobile = phone.getString("mobile");
                    //                 String home = phone.getString("home");
                    //               String office = phone.getString("office");

                    // tmp hash map for single contact
                    HashMap<String, String> posting = new HashMap<>();

                    // adding each child node to HashMap key => value
                    posting.put("id", id);
                    posting.put("type", type);
                    posting.put("slug", slug);
                    posting.put("status",status);
                    posting.put("title", title);
                    posting.put("content", content);
                    posting.put("date", date);
                    posting.put("modified", modified);


                    // adding contact to contact list
                    postList.add(posting);
                }
            } catch (final JSONException e) {
                Log.e("error", "Json parsing error: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e("er server", "Couldn't get json from server.");
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

    }

这是我的 onPost 方法:

@Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);


            Log.e("RESULT",result);

            parsejsonp(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), postList,
                    R.layout.list_item2, new String[]{"type", "slug","status",
                    "title","content","date","modified"}, new int[]{R.id.type,
                    R.id.slug,R.id.state_p,R.id.title_p, R.id.content,R.id.date_p,R.id.moddate_p});

            lv.setAdapter(adapter);
        }

但我仍然无法解析所有数据,因为仍然在我的 onPost 方法中的结果参数中我没有完整的响应

我还检查了浏览器上的 url,响应完全显示在那里。 但是如果由于缓冲区大小而没有完全显示在 logcat 中,它必须将所有数据放在我的列表视图中,但它不是

这是我的列表视图的屏幕截图

您可以看到只插入了一个对象数据但未插入其余响应,我已经调试了所有代码并检查了它存储完整对象数量的 arraylist 大小,但我的屏幕似乎只显示一个对象数据:

这是我的 layout.xml 文件,问题可能就在这里:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment">



    <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">


        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.adnan.zwd.hidoctor.Patient.Frag_two">

            <ListView
                android:id="@+id/list2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
        </RelativeLayout>




    </android.support.v4.widget.NestedScrollView>

</RelativeLayout>

行.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/type"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:text="type"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/slug"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="slug"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />
    <TextView
        android:id="@+id/state_p"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="status"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/title_p"
        android:text="title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/content"
        android:text="content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/date_p"
        android:text="date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/moddate_p"
        android:text="Mod Date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />

</LinearLayout>

关于这个问题的任何帮助,我在互联网上搜索了很多但没有成功

【问题讨论】:

  • 为什么要在这里剪断字符串 str.substring(0, 4000) ???
  • 我从这里得到了这个解决方案stackoverflow.com/questions/35546209/…
  • 我认为 String 可以容纳的最大大小是 4000 这就是为什么实际上我的 json 响应真的很大
  • 我认为 String 可以容纳的最大大小是 4000 这就是为什么实际上我的 json 响应真的很大

标签: android json substring


【解决方案1】:

它给出了解析异常。

什么例外?也许在这里?

new JSONObject(str.substring(4000));

您不能只剪掉 JSONObject 的中间部分。第一个 {[ 字符很重要。

您可以使用JsonReader class 来解析 InputStream,而不是将流读取到 BufferedReader,然后读取字符串。


或者……

你不应该从那个方法解析。该字符串已经在内存中,以便传递给该方法。

@Override
protected String doInBackground(Void... arg0) {
    HttpHandler sh = new HttpHandler();

    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url);

    Log.d("Response ==>", "Response from url: ");
    longInfo(jsonStr);
    return jsonStr;  // change your AsyncTask from Void to String return type 
}

// standalone method 
public static void longInfo(String str) {
    if(str.length() > 4000) {
        Log.i(TAG, str.substring(0, 4000));
        longInfo(str.substring(4000));
    } else
        Log.i(TAG, str);
}

这是我的 layout.xml 文件,问题可能就在这里

是的,这里有一个问题。

您不应该将 ScrollView 与 ListView 一起使用,因为 ListView 负责自己的垂直滚动

Android | ScrollView

这就是片段布局所需要的一切

<?xml version="1.0" encoding="utf-8"?>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

【讨论】:

  • 其实问题不在于解析,我得到的响应在 logcat 中是不完整的,当我使用 str.substring(0,4000);它提供了完整的 json 块,而 json 以这种方式被破坏了。并且无法解析
  • 你不应该从 logcat 中解析。你甚至不需要使用logcat,所以我不明白这个问题
  • 如果你依赖 logcat 来调试你的 API,那是错误的方法。使用像 Postman 这样的 REST 客户端来执行此操作,然后在您的应用程序中进行适当的解析
  • 我正在使用 logcat 来调试来自 url 的响应,首先我应该检查是否接收到完整的响应,然后我开始进一步解析,但是我的响应在 logcat 中显示不完整,我也尝试过解析它,但数据仅解析不完整的字符串,因此显示的数据不完整
  • 我的回复包含 10 个帖子数组,设备列表视图中只显示了一个
【解决方案2】:

我终于找到了问题所在。这一切都是因为我的布局中的 android.support.v4.widget.NestedScrollView

我通过在 nestedscrollview 中添加 android:fillViewport="true" 属性解决了这个问题

这里提到:

ListView not expanding inside NestedScrollView

【讨论】:

  • 或者你根本不应该使用 NestedScrollView,因为 ListView 已经自己滚动了
  • 你不应该将 ScrollView 与 ListView 一起使用,因为 ListView 负责自己的垂直滚动 -- developer.android.com/reference/android/widget/ScrollView.html
  • 只是最后一个混乱,如果我不使用nestedscroll,那么它会杀死appbar小部件的滚动,这是我不想要的,我想用appbar小部件的滚动行为滚动listview,这就是我使用nestedscrollview的原因
  • 那是一个单独的问题。 NestedScrollView 将绕过 FrameLayout 在 Activity 布局中,而不是在 Fragment 内
【解决方案3】:

转到 Android_Studio_Path\bin\idea.properties

更改 BufferSize 并将其增加到 2048

idea.cycle.buffer.size=1024

【讨论】:

  • 我只能在使用子字符串逻辑并且在得到它之后无法解析json对象时才能获得完整的响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 2013-03-17
相关资源
最近更新 更多