Retrofit2 上傳加密後的String數據時 會多一個雙引號

通常情況下,後臺服務器返回的數據都是json格式,所以在我們使用Retrofit2 的時候會添加addConverterFactory(GsonConverterFactory.create()),來方便解析服務器返回的數據,

new Retrofit.Builder()
                .client(client)
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

然而,在我們以Content-type:application/json 來post String參數時,會發現(後臺開發人員反饋)我們傳過去的String會多附帶一個雙引號,導致的原因是:
1.retrofit沒有內置String的Converter;
2.註冊了GsonConverterFactory,而GsonConverterFactory是不會判斷能不能處理該類型的,全部轉成json,而String在json裏就是"String"的形式(重點)

提供一種解決方案:
1.添加一個標準轉換器 converter-scalars 在GsonConverterFactory之前 代碼如下

 new Retrofit.Builder()
                .client(client)
                .baseUrl(url)
                .addConverterFactory(ScalarsConverterFactory.create())//添加的代碼
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

:標準轉換器是個獨立庫,需要在我們model的build.gradle裏單獨添加依賴,代碼如下

// 標準轉換器,去掉 Retrofit上傳參數時,String參數會多一對雙引號
    implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

其他方案:
2.自定義轉換器,此方案自行查閱資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章