预计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
答案 0 :(得分:0)
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