Moshi Retrofit error: "Expected a string but was BEGIN_OBJECT"

IgorGanapolsky picture IgorGanapolsky · May 3, 2016 · Viewed 7.6k times · Source

I built my Retrofit instance like this:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build();

Then I am calling my MockWebServer instance like this:

server.enqueue(new MockResponse().setBody(jsonStr));

Where jsonStr is built like this:

MyModel model = new MyModel("HOME", "AWAY", "ENTERTAIN", "NIGHT", "MUTE",
            "VOLUME", "SCENE 1", "SCENE 2", "SCENE 3");
JsonAdapter<MyModel> jsonAdapter = moshi.adapter(MyModel.class).toJson(model);

However, the code crashes at this point:

Response response = api.getString().execute();

The exception is:

com.squareup.moshi.JsonDataException: Expected a string but was BEGIN_OBJECT at path $

What did I do wrong?

Answer

IgorGanapolsky picture IgorGanapolsky · May 3, 2016

I found the solution: My api interface needed to have

@GET("/") Call<JsonObject> getString();

NOT

@GET("/") Call<String> getString();

The reason is that I am mocking a JSON response, not a plain String.