问题
I am parsing json data from URl but it starts with "/". I have a data class which is a POJO class in the app. Here is my json file.
/{
"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."
}
]
}
Here is my android code.
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);
I am getting an error "Expected literal value at character 0.
回答1:
just remove the "/" from the response by doing:
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);
Hope this helps
回答2:
If you only want to remove the first slash use this:
if (jsonString.substring(0, 1).equals("/") {
jsonString = jsonString.substring(1);
}
回答3:
Before parse the object just remove the "/" from json.
String jsonString = response.toString();
if (jsonString.contains("/"))
jsonString.replace("/","");
after that parse
Gson gson = new Gson();
JSONObject data1 = jsonString.getJSONObject("data");
data = gson.fromJson(data1.toString(), Data.class);
Hope it will help you!
来源:https://stackoverflow.com/questions/57070738/how-can-i-parse-json-which-starts-with-in-android-using-volley