我是GSON的新手,
几天前有人建议使用GSON,我在这里寻求帮助
我正在尝试解析此响应,但我收到了上述错误..
{
"status": 4,
"data": {
"id": 15,
"user_id": 1,
"sub_contractor_id": 1,
"battery_id": 1,
"user_long": "120.8922933",
"user_lat": "14.8185964",
"rider_long": "121.029015",
"rider_lat": "14.6496133",
"user_address_location": "313 Bantayan St, Balagtas, 3016 Bulacan, Philippines",
"complete": 1,
"created_at": "2017-04-09 15:22:07",
"updated_at": "2017-04-09 15:26:16",
"deleted_at": null,
"user": {
"id": 1,
"user_group_id": 3,
"email": "customer@motolite.com",
"created_at": null,
"updated_at": null,
"deleted_at": null
},
"battery": {
"id": 1,
"model": "Enduro",
"size": "DIN44",
"price": 2000,
"created_at": null,
"updated_at": null,
"deleted_at": null
}
}
}
我刚刚获得“状态”部分,但得到了错误。
private void fetchPosts() {
StringRequest request = new StringRequest(Request.Method.POST, ENDPOINT, onPostsLoaded, onPostsError) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", "15");
return params;
}
};
requestQueue.add(request);
}
private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("TAG", response);
List<ModelBooking> posts = Arrays.asList(gson.fromJson(response, ModelBooking[].class));
for (ModelBooking post : posts) {
Log.e("TAG", post.status);
}
}
};
private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.toString());
}
};
对于我的模特。
public class ModelBooking {
@SerializedName("status")
String status;
}
答案 0 :(得分:1)
您的JSON字符串是一个对象(它以{
开头),而不是一个数组(以[
开头)。所以你的代码会是这样的:
private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("TAG", response);
ModelBooking post = gson.fromJson(response, ModelBooking.class));
Log.e("TAG", post.status);
}
};