Reputation: 61
I am using retrofit to parse JSON. I'm getting an exception while parsing a JSON response. My response is dynamic means that when I'm getting a successful response the response key is successful, but when I'm getting a fail response it turns to an error. How can I parse that response?
When I'm getting a fail response it's giving me a proper result, but when I'm getting a successful response it's going to end in failure and gives me an exception that Expected JsonObject but was JsonPrimitive
.
Upvotes: 6
Views: 41310
Reputation: 71
I had a similar problem where server returned sometimes a JsonObject and sometimes a JsonPrimitive. When JsonPrimitive was returned I got 200 OK but it still ends up in onFailure because the types differed ( It expected a JsonObject but found a JsonPrimitive ).
public final class JsonPrimitive extends JsonElement
public final class JsonObject extends JsonElement
The com.google.gson documentation states that booth JsonPrimitive and JsonObject extend JsonElement so why not do:
JsonObject jsonObject = createJsonObject();
Call<JsonElement> requestCall = SomeInterface.sendRequest(jsonObject);
requestCall.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//Now when you get a JsonPrimitive it will still end up here because
//JsonPrimitive extends JsonElement
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
}
}
Upvotes: 6
Reputation: 205
Your API response is String and you try to get JsonObject. check your API in Postman and sure API response is JsonObject.
Upvotes: 0
Reputation: 4327
Jsonobject and jsonprimitive is different type each other .
JsonObject { "name":"John", "age":30, "car":null }
JsonPrimitive (string, number, boolean)
Your response model is wrong . try this .
http://www.jsonschema2pojo.org/
Upvotes: 2