首页 > 解决方案 > 如何使用 volley 在 android 中解析以“/”开头的 Json?

问题描述

我正在从 URl 解析 json 数据,但它以“/”开头。我有一个数据类,它是应用程序中的 POJO 类。这是我的 json 文件。

/{
    "data": [
        {
            "id": "1",
            "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        },
        {
            "id": "2",
            "text": "Felis donec et odio pellentesque diam volutpat commodo sed. Non arcu risus quis varius quam quisque. Nibh nisl condimentum id venenatis a condimentum vitae. Vel pharetra vel turpis nunc eget. "
        },
        {
            "id": "3",
            "text": "Volutpat sed cras ornare arcu dui vivamus arcu felis bibendum. Lobortis mattis aliquam faucibus purus in. Aliquam sem fringilla ut morbi tincidunt augue interdum."
        }
    ]
}

这是我的安卓代码。

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlJsonObj, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();


                try {
                    Toast.makeText(MainActivity.this, "Here", Toast.LENGTH_SHORT).show();
                    Gson gson = new Gson();
                    JSONObject data1 = response.getJSONObject("data");
                    data = gson.fromJson(data1.toString(), Data.class);

                }
                catch (JSONException e){
                    Toast.makeText(MainActivity.this, "Error : "+ e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                dataList.add(data);
                mAdapter = new ViewPagerAdapter(dataList,layoutInflater, viewPager2);

                progressBar.setVisibility(View.GONE);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            }
        });
        requestQueue.add(jsonObjectRequest);

我收到一个错误“字符 0 处的预期文字值。

标签: androidjsongsonandroid-volley

解决方案


只需通过执行以下操作从响应中删除“/”:

String subString = (respnse.tostring).replace("/","");
JSONobject jsonObj = new JSONobject(subString);
Gson gson = new Gson();
JSONObject data1 = jsonObj.getJSONObject("data");
data = gson.fromJson(data1.toString(), Data.class);

希望这可以帮助


推荐阅读