项目作者: woodyhi

项目描述 :
specify converter factory via annotation on request method
高级语言: Java
项目地址: git://github.com/woodyhi/retrofit-converter.git
创建时间: 2019-05-24T07:31:24Z
项目社区:https://github.com/woodyhi/retrofit-converter

开源协议:Apache License 2.0

下载


Download

retrofit-converter

module composite-converter 说明

Gradle依赖:

  1. dependencies {
  2. implementation 'com.github.woodyhi.retrofit:composite-converter:0.1.3'
  3. }

示例

创建retrofit,并且使用了RxJava,CompositeConverterFactory.create(Factory f)设置默认转换工厂

  1. Retrofit retrofit = new Retrofit.Builder()
  2. .baseUrl(baseUrl)
  3. .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
  4. .addConverterFactory(CompositeConverterFactory.create(GsonConverterFactory.create()))
  5. .client(okHttpClient)
  6. .build();

假设接口服务

  1. public interface ApiService {
  2. // 使用默认转换工厂
  3. @GET("user/{username}")
  4. Observable<User> getUser(@Path("username") String username);
  5. // 动态指定结果转换工厂
  6. @ResponseConverter(ScalarsConverterFactory.class)
  7. @GET("text/hello")
  8. Observable<String> hello();
  9. // 响应结果动态设置转换工厂
  10. @ResponseConverter(ScalarsConverterFactory.class)
  11. @POST("send")
  12. Observable<String> sendUserJson(@Body User user);
  13. // 请求体、响应结果 都动态指定转换工厂
  14. @RequestConverter(SimpleXmlConverterFactory.class)
  15. @ResponseConverter(ScalarsConverterFactory.class)
  16. @POST("xml")
  17. Observable<String> sendUserXml(@Body User user);
  18. }

@RequestConverter 指定请求体的转换工厂,@ResponseConverter 指定结果的转换工厂,可以不加注释使用默认转换工厂

注:注解中设置的XxxFactory.class,CompositeConverterFactory会调用其XxxFactory.create()方法。