我在Retrofit2中将自定义类实现为响应JSON时遇到了问题。
调用成功,当我记录正文(使用HttpLoggingInterceptor)时,我可以看到JSON被正确获取。
唯一的问题是它没有被解析为我创建的自定义类。
这是我的ServiceGenerator:
public class ServiceGenerator
{
//Base url for the API
public static final String API_BASE_URL = "http://base.url";
private static Retrofit.Builder GSONBuilder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <T> T createJSONService(Class<T> serviceClass)
{
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
Retrofit retrofit = GSONBuilder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
这是ServiceInterface:
public interface ServiceInterface
{
class UserResponse
{
public int id;
public String email;
public String created_at;
@Override
public String toString()
{
return "UserResponse{" +
"id: " + id +
", email: " + email +
", created_at: " + created_at +
"}";
}
}
@GET("user/{userId}")
Call<UserResponse> currentUser(@Path("userId") int userId);
}
这就是我实际上称之为的地方:
public void getUser(int userId)
{
ServiceInterface clientCreate = ServiceGenerator.createJSONService(ServiceInterface.class);
Call<ServiceInterface.UserResponse> callCreate = clientCreate.currentUser(userId);
callCreate.enqueue(new Callback<ServiceInterface.UserResponse>()
{
@Override
public void onResponse(Call<ServiceInterface.UserResponse> call, Response<ServiceInterface.UserResponse> response)
{
ServiceInterface.UserResponse user = response.body();
if (user == null)
{
System.out.println("error");
}
else
{
System.out.println(user.toString());
//This line gets printed, but the class is empty
//What it should show: UserResponse{id: 5, email: "test@email.com", created_at: "2016-03-02"}
//What it actually shows: UserResponse{id: 0, email: null, created_at: null}
}
}
@Override
public void onFailure(Call<ServiceInterface.UserResponse> call, Throwable t)
{
System.out.println("Fail: " + t.getMessage());
}
});
}
我觉得我做的一切都正确,有没有解释为什么GsonConverter没有将响应转换为我的自定义类(UserResponse)?
为了让自己更清楚,这里是实际的JSON响应(使用Postman):
{"id": 5, "email": "test@email.com", "created_at": "2016-03-02"}
提前致谢!
编辑1:
对任何有兴趣的人。
我刚才想到如果我使用String作为返回类型,它实际上会将所有数据写入String。
这意味着错误在于转换。我认为在某种程度上我错误地使用了GSONBuilder。