如何使用改造库获取对象?

how to get object with retrofit library?

我是第一次尝试使用改造库,但遇到了问题。

这是我的 JSON:

{  
   "id":"15",
   "email":"example@gmail.com",
   "phone":null,
   "password":"",
   "login":"",
   "userProfile":{ 
      "lan_status":"",
      "name":"example",
      "sex":"0",
      "second_name":"",
      "date_of_birth":"0000-00-00 00:00:00"
   }
}

这是我的改造代码:

String url = "https://example.com";
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(url)
                .build();

        mServerApi = restAdapter.create(ServerApi.class);
mServerApi.getUserInformation( new Callback <GetUserProfileInfo> () {
            @Override
            public void success(GetUserProfileInfo getUserProfileInfo, Response response) {
                saveUserInfromationToDb(mActivity, getUserProfileInfo);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

public class GetUserProfileInfo {
    @SerializedName("id")
    public int mUserId;
    @SerializedName("email")
    public String mUserEmail;
    @SerializedName("phone")
    public String mUserPhone;
    @SerializedName("password")
    public String mUserPassword;
    @SerializedName("login")
    public String mUserLogin;
    @SerializedName("userProfile")
    public List<GetUserProfileInfo_2> userProfile;

}

public class GetUserProfileInfo_2 {
    @SerializedName("lanStatus")
    public int mLanStatus;
    @SerializedName("firstName")
    public String mFirstName;
    @SerializedName("lastName")
    public String mLastName;
    @SerializedName("sex")
    public int mSex;
}

但我遇到了这个问题: retrofit.RetrofitError:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期 BEGIN_ARRAY 但在第 1 行第 533 列路径 BEGIN_OBJECT $.userProfile

很乐意提供任何帮助!

根据您的 JSON userProfile 必须是对象,而不是列表。使用 userProfile 中的所有字段创建另一个 class 并使用此 class 而不是 List<GetUserProfileInfo_2> 用于 userProfile.

public class GetUserProfileInfo {
    @SerializedName("id")
    public int mUserId;
    @SerializedName("email")
    public String mUserEmail;
    @SerializedName("phone")
    public String mUserPhone;
    @SerializedName("password")
    public String mUserPassword;
    @SerializedName("login")
    public String mUserLogin;
    @SerializedName("userProfile")
    public GetUserProfileInfo_2 userProfile;

}

看看我使用 Whosebug REST API 制作的示例应用程序,您可能会受益匪浅。我从 Retrofit 调用中得到的对象是一个对象列表,所以它看起来很符合您的需求!

https://github.com/BrunoCa/stackrest 这就是应用程序:https://play.google.com/store/apps/details?id=bruno.stackrest

享受