当前位置: 首页 > 知识库问答 >
问题:

使用GSON/POJO解析JSON

辛麻雀
2023-03-14

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

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

我得到错误:

预期BEGIN_OBJECT,但在第1行第1列路径$上是STRING

尝试解析时。

原因:java.lang.IllegalStateException:预期BEGIN_OBJECT但在第1行第1列路径$
com.google.gson.stream.JsonReader.begin对象(JsonReader.java:388)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:209)
com.google.gson.Gson.fromJson(Gson.java:879)

第192行是Post组件=gson.fromJson(响应,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\"}]}";

如果有人能帮忙,我将不胜感激。提前谢谢你。

编辑:我觉得自己像一个彻头彻尾的白痴:)结果我查询错了URL,一切正常。再次感谢大家帮助我。

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

{
  "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类:

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个答案

慎峻
2023-03-14

预期BEGIN_OBJECT,但在第1行第1列路径$上是STRING

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

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

因此,Gson正在期待JSON对象,并在找不到正确格式时引发此类异常。

这里有几种可能发生的情况。请检查它们中的每一个。

  • 您的方法是POST,请检查服务器端是否接受应用程序/x-www-form-urlencoded格式的body。正文可能需要应用程序/json或文本/纯文本等

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

董砚
2023-03-14

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类

          public class  Post{

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

               public void setResponse(String Response){

                  this.response = Response;
          } 

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

       } 

我希望这对Simon有帮助谢谢你

董桐
2023-03-14

我给你说清楚。回应应该是:

{
  "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。

 类似资料:
  • 我的如下所示: 现在,中的每个元素都有相同的结构(比如一个名为MessageDefault.java的POJO)。那么,如何将所有

  • 问题内容: 我的样子如下: 现在,每个元素具有相同的结构(假设一个POJO称为MessageDefault.java)。那么我怎么能把所有东西都当作一个??呢? 我正在使用gson进行解析。我也不能更改JSON响应。 编辑:: MessageDefault.java 它只是一切的结构。但是在JSON中,的每个子项都有不同的名称,例如POJO MessageDefault.java中所反映的名称。但

  • 我正在使用GSON解析一个JSON文件,并希望将这个JSON对象映射到一个POJO类。问题是JSON中的属性名没有camel-case,但我的java POJO对象具有camel-case属性名。 有没有任何想法没有任何表现打击? 例如:JSON文件中的属性名是'ordernumber',但在我的POJO类中,我用'Sales Number'作为属性名,而不是ordernumber。现在,我们如何

  • 问题内容: 我想使用 GSON* 在 JAVA中 解析此 JSON 文件: *** 但是我不知道如何加入root元素: 描述符 ,之后是 app3 元素,最后是 name 元素。 我遵循了本教程http://www.mkyong.com/java/gson-streaming-to-read-and-write- json/ ,但是它没有显示具有root和childs元素的情况。 问题答案: Im

  • 问题内容: 我有一个像这样的JSON文件: 在文件具有根元素之前,我将使用: 代码,但我不认为如何将类编码为根元素是一个数组。 我试过使用: 与: 但是还没有运气。使用这种方法我还能怎么读呢? PS我有这个工作使用: 但是我更想知道如何使用这两种方法(如果可能)。 问题答案: 问题是由放置在数组中的JSON对象(在 每种 情况下)的末尾逗号引起的: 如果删除它们,您的数据将成为 和 应该工作正常。