您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页Retrofit 添加返回数据为字符串的转换器

Retrofit 添加返回数据为字符串的转换器

来源:二三四教育网

addConverterFactory(new ToStringConverterFactory())

public static class ToStringConverterFactory extends Converter.Factory {        
    static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");       

    @Override        
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
         if (String.class.equals(type)) {  
              return new Converter<ResponseBody, String>() {
                    @Override
                    public String convert(ResponseBody value) throws IOException {
                        return value.string();
                    } 
               };
            }
            return null;
        }

        @Override
        public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                              Annotation[] methodAnnotations, Retrofit retrofit) {
            if (String.class.equals(type)) {
                return new Converter<String, RequestBody>() {
                    @Override
                    public RequestBody convert(String value) throws IOException {
                        return RequestBody.create(MEDIA_TYPE, value); 
                   }
                };
            }
            return null;
        }
    }

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务