簡體   English   中英

使用Volley通過GSON解析JSON時出錯

[英]Getting error when parsing JSON by GSON using Volley

如何使用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類:

儀表板Pojo_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);

錯誤日志

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)

我不知道為什么根元素是JsonArray,但由於JsonArray,最好對應於循環。 嘗試以下代碼。

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();
  }

在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);

//其中response是您從api響應中獲得的字符串

更改為您的代碼。

 Gson gson = new Gson();

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

您的json是JSONArray,因此您需要解析List<DashboardPojo_BK>而不是直接解析DashboardPojo_BK

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM