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

应为BEGIN\u数组,但在第1行第1列处为字符串

姬温文
2023-03-14

应为BEGIN\u对象,但在第1行第1列为字符串请帮助我,我遇到此错误

我的列表提供了从解析的json创建对象的类。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\u对象,但在第1行第1列为字符串

共有1个答案

狄旭
2023-03-14

格森。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
 类似资料: