Skip to content

设置Converter

liujingxing edited this page Feb 25, 2023 · 12 revisions

RxHttp提供了6个Converter,如下:

//非必须,根据自己需求选择 RxHttp默认内置了GsonConverter
implementation "com.github.liujingxing.rxhttp:converter-serialization:$rxhttp_version"
implementation "com.github.liujingxing.rxhttp:converter-fastjson:$rxhttp_version"
implementation "com.github.liujingxing.rxhttp:converter-jackson:$rxhttp_version"
implementation "com.github.liujingxing.rxhttp:converter-moshi:$rxhttp_version"
implementation "com.github.liujingxing.rxhttp:converter-protobuf:$rxhttp_version"
implementation "com.github.liujingxing.rxhttp:converter-simplexml:$rxhttp_version"

1、设置全局Converter

在初始化时,配置全局Converter,如下:

IConverter converter = FastJsonConverter.create();
RxHttpPlugins.init(OKHttpClient)
    .setConverter(converter)
    ...  //其它初始化配置

2、为请求设置单独的Converter

首先需要在任意public类中通过@Converter注解声明Converter,如下:

public class RxHttpManager {
    @Converter(name = "XmlConverter") //指定Converter名称
    public static IConverter xmlConverter = XmlConverter.create();
}

然后,rebuild 一下项目,就在自动在RxHttp类中生成setXmlConverter()方法,随后就可以调用此方法为单个请求指定Converter,如下:

RxHttp.get("/service/...")
    .setXmlConverter()   //指定使用XmlConverter,不指定,则使用全局的Converter
    .toObservable(NewsDataXml.class)
    .subscribe(dataXml -> {
        //成功回调
    }, error -> {
        //异常回调
    });