问题
In WebApi returned JSON's field can be of different class:
{ someField:"some string" }
{ someField: { "en" : "some string", "ka" : "რამე სტრინგი" } }
I've seen some solutions, but it was on previous versions of Retrofit.
How would my pojo class look like and what can i use to parse this dynamic json?
回答1:
For your case you can use Call<JsonElement>
as response type and parse it in response:
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if(response.isSuccessful()){
JsonElement jsonElement = response.body();
if(jsonElement.isJsonObject()){
JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
}
// or you can use jsonElement.getAsJsonArray() method
//use any json deserializer to convert to your class.
}
else{
System.out.println(response.message());
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
System.out.println("Failed");
}
});
来源:https://stackoverflow.com/questions/39287515/how-to-handle-response-which-can-be-different-type-in-retrofit-2