vendredi 1 juillet 2016

Retrofit2 handle JSON response that contains two models data

I'm using retrofit2 to handle http request after calling from API. Let me explain this.

I have 2 java class(POJO) created to handle user and lecturer data which is User.java and Lecturer.java respectively. For the response data such as :

{
  "users": [
    {
      "user_id": "28",
      "user_email": "john@abc.com",
      "user_password": "123"
    }
  ]
}

i can use User.java class to handle this response. Nothing complex in this file, only contains getter and setter method. Same goes to lecturer data, here is the example of lecturer data :

{
  "lecturers": [
    {
      "lecturer_id": "3",
      "user_id": "28",
      "lecturer_name": "johny2"
    }
  ]
}

i can handle it by using Lecturer.java class.

But the problem is, if the response contains both user and lecturer data on a single json, how to handle it?? . Here is the example of request :

{
  "users": [
    {
      "user_id": "28",
      "user_email": "john@abc.com",
      "user_password": "123",
      "lecturer_id": "3",
      "lecturer_name": "johny2"
    }
  ]
}

To solve this problem, i think i need to create another java class that contains both User and Lecturer class on it, unfortunately at here i'm stuck.

This is new file, that i tried to create (Userlecturer.java) :

public class UserLecturer {

  User user;
  Lecturer lecturer;

  // how to implement on this part
}

Here is UserLecturer interface :

public interface UserLecturerInterface {

  @GET ( "api/endpoint/here" )
  Call<UserLecturer> getLecturerByUserId (@Path( "userId" ) String userId );

}

Appreciated for any helps. Ask me for more inputs if above use case did't clear enough. Thanks

Aucun commentaire:

Enregistrer un commentaire