【问题标题】:Expected BEGIN_ARRAY but was STRING at line 1 column 1应为 BEGIN_ARRAY,但在第 1 行第 1 列为 STRING
【发布时间】:2014-10-10 09:29:03
【问题描述】:

应为 BEGIN_OBJECT,但在第 1 行第 1 列为 STRING 请帮助我,我收到此错误

我的列表提供类以从解析的 json 创建对象
ListOffers.java

public class ListOffers {

@SerializedName("ListOffers")
@Expose
public List<Offer> offers;

public void setListOffers(List<Offer> offers) {
    this.offers = offers;
}

public List<Offer> getListOffers() {
    return offers;
}

public ListOffers() {

}
}

 public class Offer {


public String username;
@Expose
public String title;
@Expose
public String description;
@Expose
public int discount;
@Expose
public String image1;
@Expose
public String image2;
@Expose
public String image3;
@Expose
public String image4;
public Date expiry_duration;
public Date date_posted;
}

我的 JSON :

{"offers":[  
  {  
     "username":"zara",
     "title":"zara offer",
     "description":"zara description",
     "discount":"0",
     "image1":"",
     "image2":"",
     "image3":"",
     "image4":"",
     "expiry_duration":"2014-10-21",
     "date_posted":"2014-10-07 04:01:20"
  },....
]}

使用 GSON 解析 JSON 的 MainActivity 代码 .....

try {
                    // read the server response and attempt to parse it as JSON
                    Reader reader = new InputStreamReader(content);

                    GsonBuilder gsonbuilder = new GsonBuilder();
                    gsonbuilder.setDateFormat("yy-MM-dd hh:mm:ss"); //Format of our JSON dates
                    Gson gson = gsonbuilder.create();
                    ListOffers offers = gson.fromJson(reader, ListOffers.class);
                    content.close();


                } catch (Exception ex) {
                    Log.e(TAG, "Failed to pasre JSON due to: " + ex);
                    failedLoadingOffers1();
....etc

错误:应为 BEGIN_OBJECT,但在第 1 行第 1 列为 STRING

【问题讨论】:

    标签: android json gson


    【解决方案1】:

    gson.fromJson 需要一个字符串变量,您正在向它发送一个 reader 类型的变量。

    您应该将阅读器转换为字符串。使用类似这样的东西:

    try {
      // read the server response and attempt to parse it as JSON
      BufferedReader r = new BufferedReader(new InputStreamReader(content));
      StringBuilder s = new StringBuilder();
      String line;
      while ((line = r.readLine()) != null) {
        s.append(line);
      }
      //now s has your string
      GsonBuilder gsonbuilder = new GsonBuilder();
      gsonbuilder.setDateFormat("yy-MM-dd hh:mm:ss"); //Format of our JSON dates
      Gson gson = gsonbuilder.create();
      ListOffers offers = gson.fromJson(s.toString(), ListOffers.class); //here we send s
      content.close();
    } catch (Exception ex) {
      Log.e(TAG, "Failed to pasre JSON due to: " + ex);
                        failedLoadingOffers1();
    ....etc
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2021-10-27
      • 1970-01-01
      • 2017-01-19
      • 2013-04-29
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多