0

I have this model object Courier :

public class Courier {
    @SerializedName("data")
    private List<User> data = null;

    public Courier() {
    }

    public Courier(List<User> data) {
        this.data = data;
    }

    public List<User> getData() {
        return data;
    }

    public void setData(List<User> data) {
        this.data = data;
    }
}

I get this response from server:

{
    "data": [
        {
            "id": 446,
            "courier": {
                "data": []
            },
            "title": "гром",
            "description": "Логойский тракт 24 в России в начале следующей",
            "departure": "ChIJPQKUckNv2UYRLr1NasgXZ08",
            "arrival": "EkHQodC10YDQtdCx0YDRj9C90YvQuSDQv9C10YDQtdGD0LvQvtC6LCDQnNC-0YHQutCy0LAsINCg0L7RgdGB0LjRjw"
        },
        {
            "id": 438,
            "courier": {
                "data": []
            },
            "title": "тест",
            "description": "гппг лмш ш ш ш ш г У меня на сковородке стоит ли брать сва в кино мы все равно обсуждаем",
            "departure": "ChIJH10nmDnP20YR-n7Kq6Whd5w",
            "arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
        },
        {
            "id": 439,
            "courier": {
                "data": []
            },
            "title": "лаьаьаат",
            "description": "лала слат алс ал ала ал кща да аьад",
            "departure": "ChIJH7D4cTnP20YRKlzSCnP6Mak",
            "arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
        },
        {
            "id": 442,
            "courier": {
                "data": {
                    "id": 122,
                    "email": null,
                    "phone": "73339999999",
                    "photo": null,
                    "rating": 0
                }
            },
            "title": "картошечка",
            "description": "Крупная сортированная",
            "departure": "ChIJnZRv1jnP20YRWiezW55d1tA",
            "arrival": "ChIJpfH6UJtp1EYRlhM20g-jzF4"
        }
    ]
}

If object courier not have data, i get array "data": [], if object courier has data, i get object :

"courier": {
                "data": {
                    "id": 122,
                    "email": null,
                    "phone": "73339999999",
                    "photo": null,
                    "rating": 0
                }
            }

And then I get error... Please give me advice how handle this case in android application...

nicolas asinovich
  • 3,201
  • 3
  • 27
  • 37

2 Answers2

1

is one of the most common mistakes when you start to use JSON with a client, for android please refer to this tutorial to understand

the best source to understand this kind of mistake is to read this post a canonical SO post.

Is better to read it and understand it, that asking for a simple solution because you will go really often into this error.

while deserializing, Gson was expecting a JSON object, but found a JSON array

A JSON Object is wrapped by a {

A JSON Array is wrapped by a [

What you need is to adapt your class Courier, to deserialize in the right way the JSON response.

take in mind that; a JSON array become deserialized in java as a Collection type or an array type; PLEASE notice that is confusing to use two times data

on top of everything, the first data is

public class MyPojo
{
    private Data[] data;

    public Data[] getData ()
    {
        return data;
    }

    public void setData (Data[] data)
    {
        this.data = data;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [data = "+data+"]";
    }
}

Data.class

public class Data
{
    private String id;

    private String title;

    private String description;

    private Courier courier;

    private String arrival;

    private String departure;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getTitle ()
    {
        return title;
    }

    public void setTitle (String title)
    {
        this.title = title;
    }

    public String getDescription ()
    {
        return description;
    }

    public void setDescription (String description)
    {
        this.description = description;
    }

    public Courier getCourier ()
    {
        return courier;
    }

    public void setCourier (Courier courier)
    {
        this.courier = courier;
    }

    public String getArrival ()
    {
        return arrival;
    }

    public void setArrival (String arrival)
    {
        this.arrival = arrival;
    }

    public String getDeparture ()
    {
        return departure;
    }

    public void setDeparture (String departure)
    {
        this.departure = departure;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [id = "+id+", title = "+title+", description = "+description+", courier = "+courier+", arrival = "+arrival+", departure = "+departure+"]";
    }
}

Courier.class

public class Courier
{
    private String[] data;

    public String[] getData ()
    {
        return data;
    }

    public void setData (String[] data)
    {
        this.data = data;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [data = "+data+"]";
    }
}
trocchietto
  • 2,607
  • 2
  • 23
  • 36
1

I suggest you just to create a class Data with fields id, email, etc. And make field Data data in the class Courier instead of a List<> data

EDIT: then you can use a JsonDeserializer. Just remove @SerializedName("data") over the Data field, so that the Json will not parse this field. Then create a class:

public class CourierDeserializer implements JsonDeserializer<Courier> {
    @Override
    public Courier deserialize(final JsonElement json, final Type type,
                                  final JsonDeserializationContext context) {
        Courier result = new Gson().fromJson(json, Courier.class);

        try {
            if (json != null) {
                result.setData((Data) context.deserialize(json, Data.class));
            }
        } catch (JsonParseException e) {
            result.setData(null);
        }

        return result;
    }
}

and finally register it where you create your GsonBuilder:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Courier.class, new CourierDeserializer());
mGson = gson.create();
builder.setConverter(new GsonConverter(mGson));

if you use Retrofit.

Alexander Tumanin
  • 1,638
  • 2
  • 23
  • 37