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?
@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)
yes ryan said it correct.
in java your call example will be:
Call<Response> getStuff(null,null,@FieldMap Map<String, String> options);
Remember this will work perfectly with "String" if you want to keep "int" or "float" as optional, don't use primitive data types like int, float, long, etc. Instead, use Integer, Float, Long, etc
so your example with optional integer and float will be:
Call<Response> getStuff(@Query("user_id") Integer userId, @Query("password") Float password, @FieldMap Map<String, String> options);
this syntax will take skip Integer values (handle it on server side, if needed).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.