Retrofit2学习之二:Retrofit 转换器

Converter简介

Retrofit转换器可以实现响应对象 ResponseBody 至 JavaBean对象的转换。

Wiki:https://github.com/square/retrofit/wiki/Converters

Retrofit2 Converters

1
2
3
4
5
6
7
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 Framework - com.squareup.retrofit2:converter-simpleframework
Scalars - com.squareup.retrofit2:converter-scalars
1
2
- LoganSquare - com.github.aurae.retrofit2:converter-logansquare
- FastJson - org.ligboy.retrofit2:converter-fastjson or org.ligboy.retrofit2:converter-fastjson-android

Converter使用

以Gson转换器为例,实现JSON响应体和JavaBean对象转换。

配置gradle

在app模块的build.gradle配置

1
2
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

创建业务请求接口

1
2
3
4
5
6
public interface Api {

@GET("user/info?id=1")
Call<User> getUserInfo();

}

创建一个Retrofit的实例,并配置转换器,然后利用Retrofit实例创建接口对象和调用接口方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void getRequestConverter(View view) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_ADDRESS)
.addConverterFactory(GsonConverterFactory.create()) //配置Gson转换器,调用Gson库解析json返回值
.build();

Api api = retrofit.create(Api.class);

api.getUserInfo().enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
//在UI主线程运行
if (response.isSuccessful()) {
Log.i(TAG, "返回成功");
User user = response.body();
if (user != null) {
Toast.makeText(MainActivity.this, user.getUsername(), Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onFailure(Call<User> call, Throwable t) {
Log.i(TAG, "请求失败: " + t.getLocalizedMessage());
}
});
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :