我正在尝试解析从烧瓶服务器检索到的数组。数组如下。
"[{\"firstName\": \"Roy\", \"lastName\": \"Augustine\"}]"
我正在使用以下代码在Android Studio中解析数组。
private void loadDrives() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://142.93.216.24:5000/",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
//adding the product to product list
driveList.add(new TestMl(
jsonObject.getString("firstName"),
jsonObject.getString("lastName")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
但是我遇到以下错误。
org.json.JSONException: Value [{"firstName": "Roy", "lastName": "Augustine"}] of type java.lang.String cannot be converted to JSONObject
该错误表明已成功检索json,但无法成功解析数组。有人可以提出合适的解决方案吗?
答案 0 :(得分:0)
您使用错误的名称获取数据。它是lastName
而不是lastname
更改此
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
收件人
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));