DVassilev
DVassilev

Reputation: 242

Parsing nested JSON using RetroFit for Android

I'm using RetroFit in order to communicate with my API. The response is JSON and one of JSON objects ('user') is a string. I'd like to parse that string into JSON.

I have a class for the response:

public class TokenModel {
   @SerializedName("access_token")
   private String accessToken;

   @SerializedName(".expires")
   private String expiryDate;

   private UserModel user;


   public String getAccessToken() {
       return accessToken;
   }

   public void setAccessToken(String accessToken) {
       this.accessToken = accessToken;
   }

   public String getExpiryDate() {
       return expiryDate;
   }

   public void setExpiryDate(String expiryDate) {
       this.expiryDate = expiryDate;
   }

   public UserModel getUser() {
       return user;
   }

   public void setUser(UserModel user) {
       this.user = user;
   }
}

and a class for the user:

public class UserModel {
   private int id;

   private String email;

   private String firstName;

   private String lastName;

   private String profileImageUrl; etc...

However, because the 'user' object in response is a string it needs to be first parsed into JSON. I'm unsure how to do this and still make it work with the model. Is there a way to tell RetroFit to first parse it into JSON before applying it to the model?

Thank you, Daniel

Upvotes: 1

Views: 3547

Answers (1)

DVassilev
DVassilev

Reputation: 242

Turns out to be quite simple using the advice of @corsair992.

Create a custom deserializer to parse string into Json:

public class UserDeserializer implements JsonDeserializer<UserModel> {
    @Override
    public UserModel deserialize(JsonElement jsonElement, Type typeOF,
                                 JsonDeserializationContext context)
            throws JsonParseException {
        String userString = jsonElement.getAsString();
        JsonElement userJson = new JsonParser().parse(userString);

        return new Gson().fromJson(userJson, UserModel.class);
    }
}

then set it as a converter on your rest adapter:

RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setConverter(new GsonConverter(new GsonBuilder().registerTypeAdapter(UserModel.class, new UserDeserializer()).create()))
                .setEndpoint(getString(R.string.url_base))
                .build();

That will now convert the string into Json and make it function with the model.

Upvotes: 1

Related Questions