Retrofit — Common Errors Solved

Roopashree
1 min readAug 22, 2020

In this article, I’m going to share the solutions, I identified after referring tons of articles for the issues I faced, while using Retrofit for REST API consumption.

Issue 1: If the response from the Rest API is a String, you will encounter issue in parsing the JSON. Below is the code to rectify it.

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'

ScalarsConverterFactory is the one that helps

Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/")
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

Issue 2: Failed to reach /localhost:8080/

This is occur because your virtual device will have a different IP and your server will be different. So using localhost will look for the service in the virtual device itself which is wrong.

So resolve this, use your system IP address instead of localhost or use 10.0.2.2

To identity system IP, go to Terminal in Mac or Command Prompt in Windows and type ifconfig. Your IP address will be shown.

Issue 3: Date Serialisation

If your request has Date object in it, then you might encounter issue with serialisation. If so, you can just add DateFormat in Gson as follows.

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("your ip address goes here")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

Issue 4: If you face below error, simply use setLenient() in the Gson as above.

Malformed JsonException or if your error says “Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $”

Thanks for referring my article. Happy Debugging! :)

--

--

Roopashree

Write my thoughts and learnings about life & tech. A Software Developer by profession. Love solving problems. Love to challenge myself. Love to code. Being me!