Complex JSON with generics using Retrofit2

╄→гoц情女王★ 提交于 2019-12-12 02:46:56

问题


In my application, most of the JSON that I receive from the server have the following structure:

{

"IsError":false,

"Result":{ "key1":"value", "key2":"value", ... }

}

I've followed @fernandospr 's suggestion in my original question about GSON and tried using generics to avoid writing two objects (Response and Result) per JSON and having a generic Response Object which would adapt to any kind of Result; as:

public class GenericResponse<T> {

  @SerializedName("IsError")
  private boolean isError;

  @SerializedName("Result")
  private T result;

    public boolean isError() {
      return isError;
  }

  public T result() {
      return result;
  }

}

Where I would indicate a specific Object when performing a call. The structure of the Profile Object, replacing the generic T is:

public class Profile {

  @SerializedName("UserName")
  private String userName;

  @SerializedName("Stuff")
  private boolean stuff;

  @SerializedName("ListOfStuff")
  private List<String> listOfStuff = new ArrayList<String>();

...

}

And then I perform the synchronous call like this:

Call<GenericResponse<Profile>> call = Api.getProfile(username);

  try {
    GenericResponse<Profile> response = call.execute().body();

  } catch (IOException e) {
    MUtils.logException(e);
}

Then the .body() method returns a null. I've debugged the .body() method and it seems to be working internally but the parsing doesn't work. I have reasons to believe parsing is the problem because with this simpler JSON object (doesn't require a separate Result Object) in another call .body() returns the object as it should:

public class ConfirmPasswordResponse {

  @SerializedName("isError")
  private boolean isError;

  @SerializedName("Result")
  private boolean Result;

  public boolean isError() {
      return isError;
  }

  public boolean result() {
      return Result;
  }

}

来源:https://stackoverflow.com/questions/39901077/complex-json-with-generics-using-retrofit2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!