2017-04-10 115 views
0

我很新的GSON,
几天前有人建议使用GSON,在这里我寻求一些帮助。
我试图解析这个响应,但我收到上述错误..BEGIN_ARRAY但是BEGIN_OBJECT

{ 
    "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": "[email protected]", 
     "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; 
} 
+1

我相信你的问题是重复的,你可以在互联网上找到答案。例如,看看:http://stackoverflow.com/questions/9598707/gson-throwing-expected-begin-object-but-was-begin-array –

+1

可能重复[GSON预期B​​EGIN \ _ARRAY但是BEGIN \ _Object](http://stackoverflow.com/questions/16654042/gson-expected-begin-array-but-was-begin-object) –

回答

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); 
    } 
}; 
相关问题