Android:dynamically pass model class to retrofit callback

后端 未结 10 1776
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 04:34

In retrofit to map json response to pojo usually we do this

@POST
Call getDataFromServer(@Url String url, @Body HashMap ha         


        
10条回答
  •  死守一世寂寞
    2020-12-05 05:22

    using JsonElement in Response would help:

         public interface serviceApi {
         //  @GET("userinfo")
        //  Observable getUserIfo();
        @GET("gmail/v1/users/me/profile")
        Observable> getUserProfile(@HeaderMap 
        Map Headers);
        }
    
    
    private void executeAPICall(String token) {
        HashMap headers = new HashMap<>();
        Observable> observable = RetroFitInstance.getInstance().getAPI(token)
                .getUserProfile(ImmutableMap.of("Authorization", String.format("Bearer %s", token))).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    
        Observer> observer = new Observer>() {
            @Override
            public void onCompleted() {
    
            }
    
            @Override
            public void onError(Throwable e) {
                Log.d("error:", e.getMessage());
            }
    
            @Override
            public void onNext(Response jsonElementResponse) {
                UserProfile userProfile = 
           getObject(jsonElementResponse,UserProfile.class);
    
                EmailTextView.setText("Email Address: " + 
                userProfile.getEmailAddress());
                EmailTextView.setText("Email Address: " + 
                userProfile.getEmailAddress());
                totalEmailsTextView.setText("Total Emails: " + userProfile.getMessagesTotal());
                totalThreadsTextView.setText("Total Threads: " + userProfil
        };
        subscription = observable.subscribe(observer);
    }
    
    
    private  T getObject(Response jsonElementResponse, Class 
                            t){
        return  new Gson().fromJson(jsonElementResponse.body().getAsJsonObject().toString(),t);
    }
    

提交回复
热议问题