banner
NEWS LETTER

Retrofit自定义Converter.Factory实现直接接收String

Scroll down

写在前面

在使用Retrofit过程中,通过服务器获取的数据,不一定是标准的json数据,当时就想能不能有一种方式,可以把数据直接获取到而不是解析好的数据

实现方式

创建解析器

/**
 * Retrofit 自定义Converter.Factory实现直接接收String
 */
public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    public static Converter.Factory create() {
        return new ToStringConverterFactory();
    }

    @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(@NotNull 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(@NotNull String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

其他文章
目录导航 置顶
  1. 1. 写在前面
  2. 2. 实现方式
请输入关键词进行搜索