Andre Perkins
Andre Perkins

Reputation: 7800

How to handle dots in json key fields, while using retrofit?

I am just simply trying to use retrofit to perform my rest api calls. The issue that I am facing is that when parsing the json, some of the key fields contain dots. For example:

{ "data": { "name.first": "first name"} }

Is it possible to configure Retrofit (or GsonConverter) to be able to handle this and how do I go about doing so?

Upvotes: 1

Views: 899

Answers (2)

Muneera Adil
Muneera Adil

Reputation: 53

if you are using Moshi as your JSON convertor, replace it with GSON convertor factory.

val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create()) //add this
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .client(
                        getOkHttpClient(
                            NetworkModule.networkModule.context,
                            enableNetworkInterceptor(baseUrl)
                        )
                    )

Upvotes: 0

Jake Wharton
Jake Wharton

Reputation: 76125

This is neither Retrofit nor the GsonConverter's responsibility but rather Gson which sits underneath doing the actual JSON (de)serialization.

You can use Gson's @SerializedName annotation to work around names which cannot be represented in Java:

@SerializedName("name.first")
public final String firstName;

Upvotes: 2

Related Questions