【问题标题】:Getting error when parsing JSON by GSON using Volley使用 Volley 通过 GSON 解析 JSON 时出错
【发布时间】:2017-10-18 06:18:59
【问题描述】:

如何使用 GSON 库和 Volley 解析下面的 JSON?

[
    {
        "code": 1,
        "message": "Scan Details",
        "result": [
            {
                "Inbound Date": "2017-10-13",
                "Outobund Date": "2017-10-16",
                "Inbound": "3",
                "Outbound": "3",
                "Outbound Pending": "0"
            },
            {
                "Inbound Date": "2017-10-16",
                "Outobund Date": "2017-10-16",
                "Inbound": "3",
                "Outbound": "2",
                "Outbound Pending": "1"
            }
        ]
    }
]

我已经创建了 POJO 类:

DashboardPojo_BK

import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.json.JSONObject;

public class DashboardPojo_BK implements Serializable {

    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("result")
    @Expose
    private List<ResultDashboard_BK> result = null;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<ResultDashboard_BK> getResult() {
        return result;
    }

    public void setResult(List<ResultDashboard_BK> result) {
        this.result = result;
    }

}

ResultDashboard_BK

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

public class ResultDashboard_BK implements Serializable {

    @SerializedName("Inbound Date")
    @Expose
    private String inboundDate;
    @SerializedName("Outobund Date")
    @Expose
    private String outobundDate;
    @SerializedName("Inbound")
    @Expose
    private String inbound;
    @SerializedName("Outbound")
    @Expose
    private String outbound;
    @SerializedName("Outbound Pending")
    @Expose
    private String outboundPending;

    public String getInboundDate() {
        return inboundDate;
    }

    public void setInboundDate(String inboundDate) {
        this.inboundDate = inboundDate;
    }

    public String getOutobundDate() {
        return outobundDate;
    }

    public void setOutobundDate(String outobundDate) {
        this.outobundDate = outobundDate;
    }

    public String getInbound() {
        return inbound;
    }

    public void setInbound(String inbound) {
        this.inbound = inbound;
    }

    public String getOutbound() {
        return outbound;
    }

    public void setOutbound(String outbound) {
        this.outbound = outbound;
    }

    public String getOutboundPending() {
        return outboundPending;
    }

    public void setOutboundPending(String outboundPending) {
        this.outboundPending = outboundPending;
    }

}

这是我在这里使用的发布请求,我可以解析数据,但是当 GSON 将数据设置为 POJO 类时会出现问题。

下面是我使用 Volley 库解析的JSON

 String url = Constants.BLOOMKONNECT_DASHBOARD;
    Log.e("URL",""+url);

    StringRequest eventoReq = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("RESPONSE", response.toString());

                    utils.hideDialog();
                    try {
                        JSONArray j = new JSONArray(response);

                        // Parse a json
                        for (int i = 0; i < j.length(); i++) {
                            try {
                                JSONObject obj = j.getJSONObject(0);
                                String code = String.valueOf(obj.get("code"));
                                Log.e("CODE", "" + code);

                                if(code.equals("1")){
                                    utils.showtoast("i m here");



                                    Gson gson = new Gson();
                                    Type listType = new TypeToken<ResultDashboard_BK>() {
                                    }.getType();
                                    ResultDashboard_BK pojo  = gson.fromJson(response.toString(), listType);
                                     Log.e("DATA",""+pojo);

                                } else {
                                    utils.hideDialog();
                                    utils.showtoast("Unexpected Response");
                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error: ", "" + error.getMessage());
            //hidePDialog();

        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("user_id", userId);
            Log.e("USER_ID",""+userId);
            return params;
        }
    };

    // Añade la peticion a la cola
    AppController.getInstance(this).addToRequestQueue(eventoReq);

Error_Log

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
          at com.google.gson.Gson.fromJson(Gson.java:803)
          at com.google.gson.Gson.fromJson(Gson.java:768)
          at com.google.gson.Gson.fromJson(Gson.java:717)
          at com.kabloom.kbinternal.activities.BloomKnctDashboard$3.onResponse(BloomKnctDashboard.java:142)
          at com.kabloom.kbinternal.activities.BloomKnctDashboard$3.onResponse(BloomKnctDashboard.java:118)
          at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
          at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
          at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
          at android.os.Handler.handleCallback(Handler.java:751)
          at android.os.Handler.dispatchMessage(Handler.java:95)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6165)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
       Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
          at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
          at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
          at com.google.gson.Gson.fromJson(Gson.java:803) 
          at com.google.gson.Gson.fromJson(Gson.java:768) 
          at com.google.gson.Gson.fromJson(Gson.java:717) 
          at com.kabloom.kbinternal.activities.BloomKnctDashboard$3.onResponse(BloomKnctDashboard.java:142) 
          at com.kabloom.kbinternal.activities.BloomKnctDashboard$3.onResponse(BloomKnctDashboard.java:118) 
          at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) 
          at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) 
          at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) 
          at android.os.Handler.handleCallback(Handler.java:751) 
          at android.os.Handler.dispatchMessage(Handler.java:95)

【问题讨论】:

标签: java android gson


【解决方案1】:

我不知道为什么根元素是JsonArray,但是由于JsonArray,最好对应for循环。试试下面的代码。

try {
    JSONArray j = new JSONArray(response);

    Gson gson = new Gson();
    // Parse a json
    for (int i = 0; i < j.length(); i++) {
      JSONObject obj = j.getJSONObject(i);

      DashboardPojo_BK pojo = gson.fromJson(obj.toString(), DashboardPojo_BK.class);

      if (pojo.getCode().equals("1")){
        utils.showtoast("i m here");

        // do somthing with pojo
      } else {
        utils.hideDialog();
        utils.showtoast("Unexpected Response");
      }

    }

  } catch (JSONException e) {
    e.printStackTrace();
  }

【讨论】:

    【解决方案2】:

    在您的代码中更改为这个。

     Gson gson = new Gson();
    
     Type listType = new TypeToken<List<DashboardPojo_BK>>() {}.getType();
     List<DashboardPojo_BK> mList = gson.fromJson(response.toString(), listType);
    

    【讨论】:

    • 您的代码解决了我得到的问题。谢谢你
    • 请再帮我一件事,我必须在 RecyclerView 中设置结果数据。适配器 = new InOutboundAdapter(this,mList.get(0).getResult()); recyclerView.setAdapter(适配器);如何我必须将 arrayList 发送到适配器。
    • 您可以将List&lt;DashboardPojo_BK&gt; mList设置为全局数据,您可以在您的适配器中使用它。
    • 我解决了,当我发送上下文时我不明白的一件事,我必须在适配器的构造函数中设置 Response.Listener context;以前我设置了上下文上下文;为什么我从 Activity 到 Adapter 获取上下文是 Response.Listener context; ?
    • 已解决,非常感谢@KeLiuyue
    【解决方案3】:

    在 build.gradle 文件中添加这个编译依赖

    compile 'com.google.code.gson:gson:2.8.1'
    

    然后在获得响应后,您可以使用以下方法将 json 解析为 gson

    Type listType = new TypeToken<List<DashboardPojo_BK>>(){}.getType();
    List<DashboardPojo_BK> responseModel = (List<DashboardPojo_BK>) gson.fromJson(response, listType);
    

    //reponse 是你从 api response 得到的字符串

    【讨论】:

      【解决方案4】:

      你的json是一个JSONArray,所以你需要解析List&lt;DashboardPojo_BK&gt;而不是直接解析DashboardPojo_BK

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-10
        • 2020-11-23
        相关资源
        最近更新 更多