Expected Jsonobject but Was Jsonprimitive

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.

2

3 Answers

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) {
    
    }
}

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 .

Your API response is String and you try to get JsonObject. check your API in Postman and sure API response is JsonObject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest