在使用Retrofit库进行网络请求时,有时候需要将请求参数从一个Java Object转换为Map
为了实现这个功能,我们可以使用Gson库中的toJson()方法将Java Object序列化为JSON字符串,然后将JSON字符串转换为Map
以下是代码示例:
public interface ApiService {
@POST("login")
Call login(@Body LoginRequest request);
}
public class LoginRequest {
private String email;
private String password;
public LoginRequest(String email, String password) {
this.email = email;
this.password = password;
}
}
ApiService apiService = RetrofitClient.getRetrofit().create(ApiService.class);
LoginRequest loginRequest = new LoginRequest("test@test.com", "123456");
Map paramMap = new HashMap<>();
paramMap.put("email", loginRequest.getEmail());
paramMap.put("password", loginRequest.getPassword());
String jsonString = new Gson().toJson(paramMap);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString);
Call call = apiService.login(requestBody);
在上面的代码中,我们首先定义了一个ApiService接口,包含login()方法来处理登录请求。然后我们定义了一个LoginRequest类来封装登录请求参数。
接着,我们将LoginRequest对象转换为Map
最后,我们创建了一个RequestBody对象,将JSON字符串作为请求体传递给网络请求。