1

For example i have json looks like:

{
    "data": [
        {
            "name": "one"
        },
        {
            "name": "two"
        }
    ]
}

For example i have object User with field name.

Is it possible write method which will parse data array to objects User?

something like

Call<List<User>> getUsers(@KeyPath("data"))

Now to do this, i need create a wrapper class something like

public class UsersWrapper {
    @SerializeName("data")
    public ArrayList<User> users;
}

and in service i do next

public interface Service {
    @GET("users")
    Call<UsersWrapper> getUsers()
}

But my all requests is just response with data but variable objects in array.

In this case i need create wrappers to any data requests. Pain :(

?

Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61
Dmitry Nelepov
  • 7,246
  • 8
  • 53
  • 74
  • 1
    I don't understand the question. Your response object should be an array of `User` – gilgil28 Jan 27 '16 at 15:10
  • I tend to solve that by making the call return a `JsonObject`, then chain the call in a transformer that uses a gson instance to get the list from the `JsonObject`. And then I go after the API writer until they change it. – njzk2 Jan 27 '16 at 15:27

1 Answers1

2

I'd do it this way:

Global class Wrapper<T> to parse the whole JSON

public class Wrapper<T> {
    public List<T> data;
}

And User to parse actual array;

public class User {
    public String name;
}

Then, the API interface:

@GET("/people")
Wrapper<User> getUsers();

And in DataSource class just do something like this:

@Override
public List<User> getUsers() {
    Wrapper<User> usersWrapper = myApiInterface.getUsers();
    return usersWrapper.data;
}

Upd1:
Another solution is to create custom JsonDeserializer (like described here) for List<User> type, register by registerTypeAdapter it with your custom Gson object and then you can deserialise your Json directly into List<User>. Though, this solution brings much more extra code and potential benefit is unclear for me.

Community
  • 1
  • 1
Konstantin Loginov
  • 15,802
  • 5
  • 58
  • 95
  • 1
    That works. You can also generalize that for several API calls to `class Wrapper { public List data; }` provided that your responses all use the same `data` key. – njzk2 Jan 27 '16 at 15:29