3

In WebApi returned JSON's field can be of different class:

{ someField:"some string" }
{ someField: { "en" : "some string", "ka" : "რამე სტრინგი" } }

I've seen some solutions, but it was on previous versions of Retrofit.

How would my pojo class look like and what can i use to parse this dynamic json?

K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
Nikoloz Akhvlediani
  • 403
  • 2
  • 5
  • 20

1 Answers1

1

For your case you can use Call<JsonElement> as response type and parse it in response:

call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            if(response.isSuccessful()){
                JsonElement jsonElement = response.body();
                if(jsonElement.isJsonObject()){
                    JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
                } 
                // or you can use jsonElement.getAsJsonArray() method
                //use any json deserializer to convert to your class.
            }
            else{
                System.out.println(response.message());
            }
        }
        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
            System.out.println("Failed");
        }
    });
kkost
  • 3,640
  • 5
  • 41
  • 72
  • problem with this solution is, that i have too many requests, which returns this type of fields every time. so on every call i have to use same code. I want to generalize for every call. – Nikoloz Akhvlediani Sep 02 '16 at 08:21