TarikW TarikW - 3 months ago 10
Android Question

How to add a custom field to an object before GSON parsing

I have a situation when the server returns a list of players in the team, but the player object doesn't contain the team id and I need to pass it by hand, or walk a looper after receiving

I'm using Retrofit 2.1 and Gson 2.7

I have some Gson model

public class SomeClass {

@SerializedName("fieldFromJSON")
private String mFieldFromJSON;
private String mCustomField; //<= This field is not in response

//... Empty constructor, getters and setters
}


and the Retrofit interface

@GET("some/url")
Call<List<SomeClass>> getData(
String customField //<= This I must put to all classes in customField
);


gives this response

[
{
"fieldFromJSON":"something"
}
//, {...}, ...
]


Is it possible to create
List
of
SomeClass
and put a customField to all the
SomeClass
classes by using Retrofit and Gson?

Answer

the server returns a list [...], but the [...] object doesn't contain the [...] id

Here are some options that I can think of (pardon my incomplete Retrofit code)

Option 1: Loop over the Retrofit result. At the cost of iterating over the list, this is good if you absolutely need the variable reference with each object.

final String id = "bla";

Call call = service.getData(id);
call.enqueue(new Callback<List<SomeClass>>() {

   public void onResponse(List<SomeClass> list) {
       for (SomeClass c : list) {
           c.setCustomField(id);
       }
   }

   // onError() {}
}

Option 2: Map the field to the list. You say you have a list of players on a team, and your API call appears to get those teams by ID. This is good, for example, when getting all players for all teams and you need to quickly lookup teams by ID. Essentially, you are caching the API team lookup.

final Map<String, ArrayList<SomeClass>> teamMap = new HashMap<>();

final String id = "bla";

Call call = service.getData(id);
call.enqueue(new Callback<List<SomeClass>>() {

   public void onResponse(List<SomeClass> list) {
       teamMap.put(id, list);
   }

   // onError() {}
}

Option 3: Remodel the server API to return the necessary requested field with each returned object.

Comments