0

I have an API with 2 different response:

response OK

{ "name": "test" }

response KO

[
    {
        "name_1": "test",
        "name_2": "test"
    }
]

the problem is that using Retrofit, normally, I use a model to parse results but response KO has not an array name.

How can I create a model? (I cannot change the API)

Carlos
  • 97
  • 1
  • 10

1 Answers1

1

So to add another POJO you can do this:


private static Gson gson = new GsonBuilder()

 .registerTypeAdapter(Model1.class, new GsonDeserializer<Model1>())


 .registerTypeAdapter(Model2.class, new GsonDeserializer<Model2>())

//or  create a POJO for the names array of Model2
.registerTypeAdapter(Model2.class, new GsonDeserializer<Names>())

Where GsonDeserializer is a custom serializer that can be defined, like:

public class GsonDeserializer<T> implements JsonDeserializer<T> {

@Override

public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

 JsonObject el = json.getAsJsonObject();

 return new Gson().fromJson(el, typeOfT);

}

And then in your Retrofit client you just add:


retrofit = new Retrofit.Builder()

.addConverterFactory(GsonConverterFactory.create(gson))

.build();


philoez98
  • 493
  • 4
  • 13