要使用Retrofit将值填充到已创建的POJO(Plain Old Java Object)模型对象,可以按照以下步骤进行:
implementation 'com.squareup.retrofit2:retrofit:2.x.x'
implementation 'com.squareup.retrofit2:converter-gson:2.x.x'
public class User {
private int id;
private String name;
private String email;
// 构造函数、Getter和Setter方法
}
public interface ApiService {
@GET("users/{id}")
Call getUser(@Path("id") int userId);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call call = apiService.getUser(1);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
User user = response.body();
// 填充User对象的其他字段
// 示例:打印用户信息
System.out.println("User ID: " + user.getId());
System.out.println("User Name: " + user.getName());
System.out.println("User Email: " + user.getEmail());
} else {
// 请求失败处理
System.out.println("Request failed. Error code: " + response.code());
}
}
@Override
public void onFailure(Call call, Throwable t) {
// 网络请求失败处理
t.printStackTrace();
}
});
在上面的示例中,我们首先创建了一个请求来获取ID为1的用户信息。在响应的回调函数中,我们将获取到的JSON数据填充到User对象中,并可以进一步操作这个对象。
请注意,上述代码示例中的URL、请求方法和数据模型都是示例性的,你需要根据实际情况进行相应的修改。