[英]Gson: Empty JSON conversion error
I have the following model: 我有以下模型:
public class EventSchedule {
private int id;
private String date;
private String time;
private JSONArray tickets;
private JSONArray extras;
private JSONObject venue;
public EventSchedule(int id, String date, String time, JSONArray tickets,
JSONArray extras, JSONObject venue) {
this.id = id;
this.date = date;
this.time = time;
this.tickets = tickets;
this.extras = extras;
this.venue = venue;
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public JSONArray getTickets() {
return tickets;
}
public void setTickets(JSONArray tickets) {
this.tickets = tickets;
}
public JSONArray getExtras() {
return extras;
}
public void setExtras(JSONArray extras) {
this.extras = extras;
}
public JSONObject getVenue() {
return venue;
}
public void setVenue(JSONObject venue) {
this.venue = venue;
}
}
And I have a JSON array I would like to convert to an ArrayList
of the model above using the following code: 我有一个JSON数组,我想使用以下代码转换为上述模型的
ArrayList
:
Gson gson = new Gson();
Type type = new TypeToken<List<EventSchedule>>(){}.getType();
List<EventSchedule> schedules = gson.fromJson(mEvent.getSchedules().toString(), type);
However when I try to run this my activity crashes. 但是,当我尝试运行此程序时,我的活动崩溃了。 This leads me to my first error:
这导致我遇到第一个错误:
Expected BEGIN_OBJECT but was BEGIN_ARRAY
预期为BEGIN_OBJECT,但为BEGIN_ARRAY
So I figured it was impossible to convert a model with a JSONArray
so I added transient
to exclude all the JSONArray
columns and this time it run and didn't crash. 因此,我认为用
JSONArray
转换模型是不可能的,因此我添加了transient
以排除所有JSONArray
列,这一次它运行并且没有崩溃。
Now for my second problem, whenever I tried getting the JSONObject
venue it always turned up empty. 现在,对于第二个问题,每当我尝试获取
JSONObject
场所时,它总是变成空的。 I do not know why. 我不知道为什么。
So my question now is how do I solve my issue with JSONArray
and JSONObject
so that I am able to convert to an ArrayList
. 因此,我现在的问题是如何解决
JSONArray
和JSONObject
问题,以便能够转换为ArrayList
。
Expected BEGIN_OBJECT but was BEGIN_ARRAY
预期为BEGIN_OBJECT,但为BEGIN_ARRAY
The reason you are getting this error is because you have declare object in your class. 出现此错误的原因是因为您在类中声明了对象。
private JSONArray tickets; //Object ref. of JSONArray
private JSONArray extras; //Object ref. of JSONArray
However your response consisting List of objects so during conversion it find object instead of List 但是,您的响应包含对象列表,因此在转换过程中它将找到对象而不是列表
Solution : 解决方案:
Make a class which is will represent your JSONObject in your JSONArray and use it instead in List tickets; 创建一个将在JSONArray中表示您的JSONObject的类,并在List票证中使用它;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.