简体   繁体   English

改造2 @FormUrl使用空字段编码

[英]Retrofit 2 @FormUrlEncoded with null fields

I'm sending this: 我发送此:

@FormUrlEncoded
@PUT("Devices/{id}")
Call<Device> updateDeviceSync(
        @Path("id") String id,
        @Field("fieldName1") Integer fieldName1,
        @Field("fieldName2") String fieldName2,
        @Field("fieldName3") String fieldName3);

I'm calling it with: 我这样称呼:

apiService.updateDeviceSync(deviceId, 0, null, timestamp)

But its only sending fieldName1 and fieldName3 但它仅发送fieldName1fieldName3

I already have serializeNulls() on my gsonbuilder so it should include nulls in there but logcat shows that its not including fieldName2 我的gsonbuilder上已经有serializeNulls() ,所以它应该在那里包含null,但是logcat显示它不包括fieldName2

I need to update fieldName2 to null in retrofit2 我需要在Retrofit2中将fieldName2更新为null

Generally you do not want to send nulls in your API requests. 通常,您不希望在API请求中发送null。 Your server will look for the field and see that it is not there. 您的服务器将查找该字段,并发现该字段不存在。 By not sending the nulls you save on bandwidth and in turn save on data/battery. 通过不发送空值,您可以节省带宽,进而节省数据/电池。

Finally made it work, Here are the changes I made: 终于使它工作了,这是我所做的更改:

Updated my api to: 我的api更新为:

@PUT("Devices/{id}")
Call<Device> updateDeviceCurfewSync(             
    @Path("id") String id,
    @Body HashMap<String, Object> data);

Then called: 然后称为:

HashMap<String, Object> deviceSyncMap = new HashMap<>();
deviceSyncMap.put("fieldName1", 0);
deviceSyncMap.put("fieldName2", null);
deviceSyncMap.put("fieldName3", timestamp);

apiService.updateDeviceCurfewSync(deviceId, deviceSyncMap)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM