Simply,use GsonConverterFactory
, before use that you need add this to your gradle file:
compile 'com.squareup.retrofit:converter-gson'
Let's say you have a Object called LoginResponse
and it has a attribute called loginResult
:
public class LoginResponse{
LoginResult loginResult;
}
The LoginResult
object define is like this:
public class LoginResult{
int result;
long userId;
...
}
Then use Retrofit
to request:
public interface APIService {
@POST("SOMETHING/login")
Call<LoginResponse> doLogin();
}
public void doSomething() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("YOUR LOGIN BASE URL")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<LoginResponse> loginCall = service.doLogin();
//if you want to request synchronous:
LoginResponse response = loginCall.execute();
//if you want to request asynchronous:
LoginResponse response = loginCall.enqueue(new Callback<LoginResponse>() {
@Override void onResponse(/* ... */) {
// ...
}
@Override void onFailure(Throwable t) {
// ...
}
});
}
When you get the LoginResponse
, you can do you work:
if(response.loginResult.result == 2){
//do work here.something like startActivity(...);
}
Reference:
- https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/
- http://inthecheesefactory.com/blog/retrofit-2.0/en