【问题标题】:Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path [duplicate]应为 BEGIN_ARRAY,但在第 1 行第 2 列路径中为 BEGIN_OBJECT [重复]
【发布时间】:2017-03-03 18:24:48
【问题描述】:

我/我试图使用 GSON 将 json 放入 recyclerview,但是当我运行它时,它给了我“预期 BEGIN_ARRAY 但在第 1 行第 2 列路径 $ 处是 BEGIN_OBJECT”错误!

这是我的 json:

{"action":"true","error":"","data":[{"_id":"58ad8d8ca49d0e11e21c4504","store_name":"firstStore","store_view":0,"store_textposition":null},{"_id":"58ad9063cb35f5977b55dfd6","store_name":"firstStorestest","store_view":0,"store_textposition":null},{"_id":"58ad9088cb35f5977b55dfd7","store_name":"firstStorestest","store_view":0,"store_textposition":null}]}

这是我得到错误的地方:

    private void requestJsonObject(){
    RequestQueue queue = Volley.newRequestQueue(getContext());
    String url ="MYURL";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Response " + response);
            GsonBuilder builder = new GsonBuilder();
            Gson mGson = builder.create();
            List<ItemObject> posts = new ArrayList<ItemObject>();
            posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
            adapter = new RecyclerViewAdapter(getActivity(), posts);
            recyclerView.setAdapter(adapter);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.getMessage());
        }
    });
    queue.add(stringRequest);
}

这里是 Itemobject.java

public class ItemObject {
@SerializedName("store_name")
private String store_name;
@SerializedName("store_textposition")
private String store_textposition;
@SerializedName("store_view")
private String store_view;
@SerializedName("_id")
private String _id;
public ItemObject(String store_name, String store_textposition, String store_view, String _id) {
    this.store_name = store_name;
    this.store_textposition = store_textposition;
    this.store_view = store_view;
    this._id = _id;
}
public String getStore_name() {
    return store_name;
}
public String getStore_textposition() {
    return store_textposition;
}
public String getStore_view() {
    return store_view;
}
public String get_id(){
    return _id;
}

这有什么问题?

【问题讨论】:

标签: java android json gson


【解决方案1】:

您的响应以 Object 开头,但您以前转换为 Array。

编辑

创建一个类。

Class Test
{
    @SerializedName("data")
    private List<ItemObject> data;
}

然后在解析的时候写下这段代码:

        Gson mGson = builder.create();
        Test test=mGson.fromJson(response, Test.class)

【讨论】:

  • 你能告诉我该怎么做吗?或者要改变什么@asif-patel
  • @akdhbuhi mGson.fromJson(response, ItemObject[].class)... 您的数据不是ItemObject[],因为它以{ 字符开头,而不是[ 字符。在使用 Gson 之前,您需要从 JSON 中提取 "data"
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2018-05-23
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2021-08-02
相关资源
最近更新 更多