如何使用 volley 解析 android 中以“/”开头的 Json?

How can I parse Json which starts with "/" in android using volley?

我正在解析来自 URl 的 json 数据,但它以“/”开头。 我有一个数据 class,它是应用程序中的一个 POJO class。 这是我的 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."
        }
    ]
}

这是我的 android 代码。

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 处的预期文字值。

在解析对象之前,只需从 json 中删除“/”。

String jsonString = response.toString();
if (jsonString.contains("/"))
   jsonString.replace("/","");

之后解析

 Gson gson = new Gson();
 JSONObject data1 = jsonString.getJSONObject("data");
 data = gson.fromJson(data1.toString(), Data.class);

希望对您有所帮助!

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

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

希望对您有所帮助

如果您只想删除第一个斜杠,请使用:

if (jsonString.substring(0, 1).equals("/") {
    jsonString = jsonString.substring(1);
}