Get nested JSON object with GSON using retrofit

前端 未结 13 980
挽巷
挽巷 2020-11-22 17:04

I\'m consuming an API from my android app, and all the JSON responses are like this:

{
    \'status\': \'OK\',
    \'reason\': \'Everything was fine\',
    \         


        
13条回答
  •  旧时难觅i
    2020-11-22 17:25

    Had the same problem couple of days ago. I've solve this using response wrapper class and RxJava transformer, which I think is quite flexiable solution:

    Wrapper:

    public class ApiResponse {
        public String status;
        public String reason;
        public T content;
    }
    

    Custom exception to throw, when status is not OK:

    public class ApiException extends RuntimeException {
        private final String reason;
    
        public ApiException(String reason) {
            this.reason = reason;
        }
    
        public String getReason() {
            return apiError;
        }
    }
    

    Rx transformer:

    protected  Observable.Transformer, T> applySchedulersAndExtractData() {
        return observable -> observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(tApiResponse -> {
                    if (!tApiResponse.status.equals("OK"))
                        throw new ApiException(tApiResponse.reason);
                    else
                        return tApiResponse.content;
                });
    }
    

    Example usage:

    // Call definition:
    @GET("/api/getMyPojo")
    Observable> getConfig();
    
    // Call invoke:
    webservice.getMyPojo()
            .compose(applySchedulersAndExtractData())
            .subscribe(this::handleSuccess, this::handleError);
    
    
    private void handleSuccess(MyPojo mypojo) {
        // handle success
    }
    
    private void handleError(Throwable t) {
        getView().showSnackbar( ((ApiException) throwable).getReason() );
    }
    

    My topic: Retrofit 2 RxJava - Gson - "Global" deserialization, change response type

提交回复
热议问题