将数组从 Flask 解析为 Android
Parsing an array from Flask to Android
我正在尝试解析从 Flask 服务器检索到的数组。数组如下。
"[{\"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正在成功获取,但无法成功解析数组。有人可以提出合适的解决方案吗?
您使用错误的名称获取数据..它是 lastName
而不是 lastname
改变这个
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
到
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));
我正在尝试解析从 Flask 服务器检索到的数组。数组如下。
"[{\"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正在成功获取,但无法成功解析数组。有人可以提出合适的解决方案吗?
您使用错误的名称获取数据..它是 lastName
而不是 lastname
改变这个
driveList.add(new TestMl(
array.getString("firstname"),
array.getString("lastname")
));
到
driveList.add(new TestMl(
array.getString("firstName"),
array.getString("lastName")
));