android – Retrofit optional and required fields-ThrowExceptions

Exception or error:

When using Retrofit, I know you can use @FieldMap Map<String, String> options to specify optional queries.

Say that I have a api call that had 2 required fields and 3 optional fields.

How would I format these calls?

Would it be something like

Call<Response> getStuff(@Query("user_id") String userId, @Query("password") String password, @FieldMap Map<String, String> options)

or would the entire thing be a single @FieldMap like:

Call<Response> getStuff(@FieldMap Map<String, String> options)

and with this option would you just fill in the required fields and then use null for the optionals?

How to solve:

@FieldMap and @Query params both support optional fields. As you mentioned, simply pass null if you don’t want to pass a value.


I have stuck in the question several hours and finally resolve the question.

I’ ll use Kotlin to answer the question.

As @Ryan said, you can also just pass null as the value in Kotlin:

fun getStuff(@Query("user_id") userId: String? = null ,
                 @Query("password") password: String? = null,
                 @FieldMap options: Map<String, String>? = null): Call<Response>

If you have a optional fields like @Query("page") int page in Java, there is something that you should keep in mind:

In Java, you can’t pass null for primitive data types like int, float, long, etc.

Instead, use Integer, Float, Long, etc and the compiler won’t be grumpy.

So the correct answer is: @Query("page") Integer page.

And in Kotlin, you can’t pass null for primitive data types like Int, Float, Long, etc.

Using Int? instead of Int and Retrofit will ignore them while assembling the request.

This is because while Kotlin compile on the JVM, non-nullable values of this type are represented as values of the primitive type int, nullable value like Int? is a boxed Type.

So in Kotlin, a nullable Int Int? can solve this question.

For more information about Kotlin primitive, see: What is the difference between Int and Integer in Kotlin?

I hope it helped somebody also.


Retrofit2 (unlike Retrofit1) does not accept null values in @FiledMap (throws exception).
Null-values passed to @Field/@Query params are ignored (do not appear in http-request)

Leave a Reply

Your email address will not be published. Required fields are marked *