问题
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