Expected JsonObject but was JsonPrimitive
Solution 1
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) {
}
}
Solution 2
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/
Admin
Updated on June 09, 2022Comments
-
Admin almost 2 years
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
.