成功登录会从服务器返回以下JSONObject
:
{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}
我想将response_data
信息放入我的User
对象中。我以前做过这样的事情:
String getResponse = jsonObject.getString("response_data");
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
//All the data in the `response_data` is initialized in `User`
User user = gson.fromJson(getResponse, User.class);
现在我尝试在改造中做同样的事情:
初始化RestAdapter +接口:
public class ApiClient {
private static RetrofitService sRetrofitService;
public static RetrofitService getRetrofitApiClient() {
if (sRetrofitService == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint("http://xxx.xxx.xxx.xxx/")
.build();
sRetrofitService = restAdapter.create(RetrofitService.class);
}
return sRetrofitService;
}
public interface RetrofitService {
@FormUrlEncoded
@POST("/login")
public void login(@Field("email_id") String emailId, @Field ("password") String password,
Callback <User> callback);
}
}
MainActivity:
ApiClient.getRetrofitApiClient().login(email.getText().toString(), password.getText().toString(),
new Callback<User>() {
@Override
public void success(User user, Response response) {
User user1 = user; //null
Toast.makeText(this, "user is: "+user1.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(this, "Failed Login", Toast.LENGTH_SHORT).show();
}
});
用户:
public class User {
private String userId;
private String emailId;
private String code;
public User() {
}
... getters
... setters
}
Retrofit
中的MainActivity
代码有效,我在log
中收到此回复:
{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}
但是它不会将response_data
解析为我的User
对象。
我该如何解决这个问题?
答案 0 :(得分:5)
您需要创建一个响应对象
public class UserResponse {
private User responseData;
private String message;
private boolean success;
}
并更改您的回调以返回UserResponse
public interface RetrofitService {
@FormUrlEncoded
@POST("/login")
public void login(@Field("email_id") String emailId, @Field ("password") String password,
Callback <UserResponse> callback);
}
注意:您还需要创建自定义Gson实例,并将其应用于其余适配器。
RestAdapter restAdapter = RestAdapter.Builder()
.setEndpoint("xxx")
.setConverter(new GsonConverter(gson))
.build()
答案 1 :(得分:1)
首先,
setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
你想要
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
这就是你的字段的命名方式。 (例如response_data
)
然后,您的User
课程不代表您服务的答案。创建一个模仿json对象结构的模型类。 (正如cyroxis所建议的那样)。
最后,您的java成员的命名与您的json字段的命名不一致(例如,用户中的secret_code
vs code
。修复此问题,或使用@SerializedName
将json字段显式匹配到java字段。
答案 2 :(得分:1)
如果你做了两件事,它可能会解决你的问题: