sungerk的专栏

'or'=='or'

retrofit2.0转换String 报错修复

添加Gson转换支持

new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(AppVars.RequestPath.BASE_URL)
                    .client(App.getOkHttpClient())
                    .build();

然后这样设置后 Call< String>会出现gson类型转换异常

需要添加字符串转换


import com.squareup.okhttp.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;

import retrofit.Converter;

/**
 * retrofit转换成字符串支持
 * Created by Administrator on 2015/11/19.
 */
public final class StringConverterFactory extends Converter.Factory {
    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    @Override
    public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
        return new ConfigurationServiceConverter();
    }

    final class ConfigurationServiceConverter implements Converter<ResponseBody, String> {

        @Override
        public String convert(ResponseBody value) throws IOException {
            BufferedReader r = new BufferedReader(new InputStreamReader(value.byteStream()));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            return total.toString();
        }
    }
}

最后添加

 retrofit = new Retrofit.Builder().addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(AppVars.RequestPath.BASE_URL)
                    .client(App.getOkHttpClient())
                    .build();
阅读更多
版权声明:本文为sunger原创文章,未经博主允许不得转载。 我的微博http://weibo.com/sungerk https://blog.csdn.net/s228245214/article/details/49927435
个人分类: android
上一篇RecyclerView cardview点击效果
下一篇Android 控件未渲染完成操作控件错误解决方案
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭