转化器
默认情况下, Retrofit只能将HTTP请求体反序列化为OkHttp的ResponseBody
类型, 并且在@Body
中只能接受RequestBody
类型.
可以添加转化器以便支持其他类型. 为了您的使用便捷, 已经有6种模块适配了流行的序列化库.
- Gson: com.squareup.retrofit2:converter-gson
- Jackson: com.squareup.retrofit2:converter-jackson
- Moshi: com.squareup.retrofit2:converter-moshi
- Protobuf: com.squareup.retrofit2:converter-protobuf
- Wire: com.squareup.retrofit2:converter-wire
- Simple XML: com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
以下是使用GsonConverterFactory
类生成一个使用Gson进行反序列化的GitHubService
接口实现类的示例.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);