使用GSON / POJO解析JSON

时间:2016-03-29 06:38:36

标签: java android json gson

我正在使用volley + OkHttp从服务器获取一些数据。

响应是一个包含JSON的字符串,我想用GSON / POJO解析它。

我收到错误:

  

预计BEGIN_OBJECT但在STRING第1行第1道路$

尝试解析时。

  

引起:java.lang.IllegalStateException:预期BEGIN_OBJECT但是在第1行第1行STRING STRING   在com.google.gson.stream.JsonReader.beginObject(JsonReader.java:388)
  在com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:209)
  在com.google.gson.Gson.fromJson(Gson.java:879)
  在com.google.gson.Gson.fromJson(Gson.java:844)
  在com.google.gson.Gson.fromJson(Gson.java:793)
  在com.google.gson.Gson.fromJson(Gson.java:765)
  at test.com.example.buddy.myapplication.MainActivity $ 8.onResponse(MainActivity.java:192)       //

第192行是Post component = gson.fromJson(response, Post.class);

另一方面,当我在 JSON_STRING 下方使用时,它按预期工作,我使用POJO类获取值。

String JSON_STRING = "{\"currentBalance\":{\"amount\":0.0,\"currencyCode\":\"EUR\"},\"currentBalanceDisplay\":true,\"overdueAmount\":null,\"overdueAmountDisplay\":false," +
                     "\"creditAmount\":null,\"creditAmountDisplay\":false,\"noOfBillsToShow\":3,\"recentBills\":[{\"period\":\"03 2016\",\"amount\":{\"amount\":22.76," +
                     "\"currencyCode\":\"EUR\"},\"status\":\"PAID\",\"dueDate\":\"14-03-2016\",\"sortOrder\":\"20160308\",\"periodType\":\"MONTHLY\"," +
                     "\"invoiceId\":\"277726719\",\"invoiceDate\":\"08-03-2016\"}]}";

如果有人可以提供帮助,我将不胜感激。提前谢谢。

编辑:我觉得自己像个完全白痴:)事实证明我正在查询错误的网址,一切都按预期工作。再次感谢各位帮助我的人。

来自服务器的字符串响应:

{
  "currentBalance": {
    "amount": 0.0,
    "currencyCode": "EUR"
  },
  "currentBalanceDisplay": true,
  "overdueAmount": null,
  "overdueAmountDisplay": false,
  "creditAmount": null,
  "creditAmountDisplay": false,
  "noOfBillsToShow": 3,
  "recentBills": [
    {
      "period": "03 2016",
      "amount": {
        "amount": 12.53,
        "currencyCode": "EUR"
      },
      "status": "PAID",
      "dueDate": "14-03-2016",
      "sortOrder": "2548264",
      "periodType": "MONTHLY",
      "invoiceId": "012345678",
      "invoiceDate": "08-03-2016"
    }
  ]
}

排球要求:

private void FetchData() {

StringRequest finalrequest = new StringRequest(Request.Method.POST, FETCHURL,
      new Response.Listener<String>() {

          @Override
          public void onResponse(String response) {

                 Gson gson = new Gson();
                 Post component = gson.fromJson(response, Post.class);
                 System.out.println("JSON " + component.getRecentBills().get(0).getInvoiceDate());
                 // Output: JSON 08-03-2016 (success!)
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("ERROR", "error finalrequest => " + error.toString());
            }
        }
) {
    @Override
    public String getBodyContentType() {
        return "application/x-www-form-urlencoded; charset=utf-8";
    }

    // this is the relevant method
    @Override
    public byte[] getBody() {

        String httpPostBody = "action=GET_CUST_BILLS&" + "user=" + CustID;
        try {
            httpPostBody = httpPostBody + URLEncoder.encode("", "UTF-8");

        } catch (UnsupportedEncodingException exception) {

            Log.e("ERROR", "exception", exception);
            // return null and don't pass any POST string if you encounter encoding error
            return null;
        }
        Log.d("POSTBODY ", httpPostBody.toString());
        return httpPostBody.getBytes();
    }
};
finalrequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 5,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,  DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    TestController.getInstance().addToRequestQueue(finalrequest, "Final");
  }

POJO Post class:

public class Post {

    private CurrentBalanceBean currentBalance;
    private boolean currentBalanceDisplay;
    private Object overdueAmount;
    private boolean overdueAmountDisplay;
    private Object creditAmount;
    private boolean creditAmountDisplay;
    private int noOfBillsToShow;

    private List<RecentBillsBean> recentBills;

    public static Post objectFromData(String str) {

        return new Gson().fromJson(str, Post.class);
    }

    public static Post objectFromData(String str, String key) {

        try {
            JSONObject jsonObject = new JSONObject(str);

            return new Gson().fromJson(jsonObject.getString(str), Post.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static List<Post> arrayPostFromData(String str) {

        Type listType = new TypeToken<ArrayList<Post>>() {
        }.getType();

        return new Gson().fromJson(str, listType);
    }

    public static List<Post> arrayPostFromData(String str, String key) {

        try {
            JSONObject jsonObject = new JSONObject(str);
            Type listType = new TypeToken<ArrayList<Post>>() {
            }.getType();

            return new Gson().fromJson(jsonObject.getString(str), listType);

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

        return new ArrayList();


    }

    public CurrentBalanceBean getCurrentBalance() {
        return currentBalance;
    }

    public void setCurrentBalance(CurrentBalanceBean currentBalance) {
        this.currentBalance = currentBalance;
    }

    public boolean isCurrentBalanceDisplay() {
        return currentBalanceDisplay;
    }

    public void setCurrentBalanceDisplay(boolean currentBalanceDisplay) {
        this.currentBalanceDisplay = currentBalanceDisplay;
    }

    public Object getOverdueAmount() {
        return overdueAmount;
    }

    public void setOverdueAmount(Object overdueAmount) {
        this.overdueAmount = overdueAmount;
    }

    public boolean isOverdueAmountDisplay() {
        return overdueAmountDisplay;
    }

    public void setOverdueAmountDisplay(boolean overdueAmountDisplay) {
        this.overdueAmountDisplay = overdueAmountDisplay;
    }

    public Object getCreditAmount() {
        return creditAmount;
    }

    public void setCreditAmount(Object creditAmount) {
        this.creditAmount = creditAmount;
    }

    public boolean isCreditAmountDisplay() {
        return creditAmountDisplay;
    }

    public void setCreditAmountDisplay(boolean creditAmountDisplay) {
        this.creditAmountDisplay = creditAmountDisplay;
    }

    public int getNoOfBillsToShow() {
        return noOfBillsToShow;
    }

    public void setNoOfBillsToShow(int noOfBillsToShow) {
        this.noOfBillsToShow = noOfBillsToShow;
    }

    public List<RecentBillsBean> getRecentBills() {
        return recentBills;
    }

    public void setRecentBills(List<RecentBillsBean> recentBills) {
        this.recentBills = recentBills;
    }

    public static class CurrentBalanceBean {
        private int amount;
        private String currencyCode;

        public static CurrentBalanceBean objectFromData(String str) {

            return new Gson().fromJson(str, CurrentBalanceBean.class);
        }

        public static CurrentBalanceBean objectFromData(String str, String key) {

            try {
                JSONObject jsonObject = new JSONObject(str);

                return new Gson().fromJson(jsonObject.getString(str), CurrentBalanceBean.class);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        public static List<CurrentBalanceBean> arrayCurrentBalanceBeanFromData(String str) {

            Type listType = new TypeToken<ArrayList<CurrentBalanceBean>>() {
            }.getType();

            return new Gson().fromJson(str, listType);
        }

        public static List<CurrentBalanceBean> arrayCurrentBalanceBeanFromData(String str, String key) {

            try {
                JSONObject jsonObject = new JSONObject(str);
                Type listType = new TypeToken<ArrayList<CurrentBalanceBean>>() {
                }.getType();

                return new Gson().fromJson(jsonObject.getString(str), listType);

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

            return new ArrayList();


        }

        public int getAmount() {
            return amount;
        }

        public void setAmount(int amount) {
            this.amount = amount;
        }

        public String getCurrencyCode() {
            return currencyCode;
        }

        public void setCurrencyCode(String currencyCode) {
            this.currencyCode = currencyCode;
        }
    }

    public static class RecentBillsBean {
        private String period;
        /**
         * amount : 22.76
         * currencyCode : EUR
         */

        private AmountBean amount;
        private String status;
        private String dueDate;
        private String sortOrder;
        private String periodType;
        private String invoiceId;
        private String invoiceDate;

        public static RecentBillsBean objectFromData(String str) {

            return new Gson().fromJson(str, RecentBillsBean.class);
        }

        public static RecentBillsBean objectFromData(String str, String key) {

            try {
                JSONObject jsonObject = new JSONObject(str);

                return new Gson().fromJson(jsonObject.getString(str), RecentBillsBean.class);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        public static List<RecentBillsBean> arrayRecentBillsBeanFromData(String str) {

            Type listType = new TypeToken<ArrayList<RecentBillsBean>>() {
            }.getType();

            return new Gson().fromJson(str, listType);
        }

        public static List<RecentBillsBean> arrayRecentBillsBeanFromData(String str, String key) {

            try {
                JSONObject jsonObject = new JSONObject(str);
                Type listType = new TypeToken<ArrayList<RecentBillsBean>>() {
                }.getType();

                return new Gson().fromJson(jsonObject.getString(str), listType);

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

            return new ArrayList();


        }

        public String getPeriod() {
            return period;
        }

        public void setPeriod(String period) {
            this.period = period;
        }

        public AmountBean getAmount() {
            return amount;
        }

        public void setAmount(AmountBean amount) {
            this.amount = amount;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getDueDate() {
            return dueDate;
        }

        public void setDueDate(String dueDate) {
            this.dueDate = dueDate;
        }

        public String getSortOrder() {
            return sortOrder;
        }

        public void setSortOrder(String sortOrder) {
            this.sortOrder = sortOrder;
        }

        public String getPeriodType() {
            return periodType;
        }

        public void setPeriodType(String periodType) {
            this.periodType = periodType;
        }

        public String getInvoiceId() {
            return invoiceId;
        }

        public void setInvoiceId(String invoiceId) {
            this.invoiceId = invoiceId;
        }

        public String getInvoiceDate() {
            return invoiceDate;
        }

        public void setInvoiceDate(String invoiceDate) {
            this.invoiceDate = invoiceDate;
        }

        public static class AmountBean {
            private double amount;
            private String currencyCode;

            public static AmountBean objectFromData(String str) {

                return new Gson().fromJson(str, AmountBean.class);
            }

            public static AmountBean objectFromData(String str, String key) {

                try {
                    JSONObject jsonObject = new JSONObject(str);

                    return new Gson().fromJson(jsonObject.getString(str), AmountBean.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }

            public static List<AmountBean> arrayAmountBeanFromData(String str) {

                Type listType = new TypeToken<ArrayList<AmountBean>>() {
                }.getType();

                return new Gson().fromJson(str, listType);
            }

            public static List<AmountBean> arrayAmountBeanFromData(String str, String key) {

                try {
                    JSONObject jsonObject = new JSONObject(str);
                    Type listType = new TypeToken<ArrayList<AmountBean>>() {
                    }.getType();

                    return new Gson().fromJson(jsonObject.getString(str), listType);

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

                return new ArrayList();


            }

            public double getAmount() {
                return amount;
            }

            public void setAmount(double amount) {
                this.amount = amount;
            }

            public String getCurrencyCode() {
                return currencyCode;
            }

            public void setCurrencyCode(String currencyCode) {
                this.currencyCode = currencyCode;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

我会告诉你的。 答案应该是:

{
  "currentBalance": {
    "amount": 0.0,
    "currencyCode": "EUR"
  },
  "currentBalanceDisplay": true,
  "overdueAmount": null,
  "overdueAmountDisplay": false,
  "creditAmount": null,
  "creditAmountDisplay": false,
  "noOfBillsToShow": 3,
  "recentBills": [
    {
      "period": "03 2016",
      "amount": {
        "amount": 12.53,
        "currencyCode": "EUR"
      },
      "status": "PAID",
      "dueDate": "14-03-2016",
      "sortOrder": "2548264",
      "periodType": "MONTHLY",
      "invoiceId": "012345678",
      "invoiceDate": "08-03-2016"
    }
  ]
}

但是,你得到:

"Request cannot be served without a proper action"

如果您不拥有服务器,我想您使用的是来自提供商的API。您应该正确检查他们的文档。我猜,你错过了一个参数,或者他们需要你为你的请求添加一些cookie。

答案 1 :(得分:2)

1)将您的Json存储在Pojo类中 2)将Pojo类对象转换为Gson。

示例:

   @Override
       public void onResponse(String response) {

           Gson gson = new Gson();
                 Post object = new Post();
                 object.setResponse(response);
          String gson = gson.fromJson(object, Post.class);//as you have overrided toString() it will return you the response you have set
           System.out.println(gson);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                        // Handle error
                }
            }

Pojo CLASS

          public class  Post{

                  private String resposne;
              private int example;
               ....

               public void setResponse(String Response){

                  this.response = Response;
          } 

      @Override
        public String toString() {
           return  response;
            }

       } 

我希望这对simon有帮助。 THANKYOU

答案 2 :(得分:1)

  

预计BEGIN_OBJECT但在STRING第1行第1道路$

当您从服务器获得HTML响应时,这是一个常见的JSON解析问题。

<html>
<body>
<h1>404 Not Found</h1>
</body>
</html>

因此Gson期待一个JSON对象,并在找不到正确的格式时抛出此类异常。

这里可能会发生几种情况。请检查每一个。

  • 您的方法是POST,请检查服务器端是否接受application/x-www-form-urlencoded格式的正文。正文可能会期待application/jsontext/plain等。
  • 检查参数是否正确传递。
  • 如果您的身边没有任何问题,您可能也必须检查服务器端。检查它是否可以处理您的请求,并可以使用您期望的正确数据进行响应。

尝试使用Postman来模拟请求和响应。调试这种情况要快得多。