简体   繁体   中英

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:

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

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.

Now for my second problem, whenever I tried getting the JSONObject venue it always turned up empty. 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 .

Expected BEGIN_OBJECT but was 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM