2015-09-06 87 views
18

我正在爲教育目的製作一個簡單的RetroFit應用程序,並將IntelliJ IDEA用作我的IDE。如何在RetroFit中使用Gson轉換器?

我已經正確導入了Retrofit庫(至少我認爲我有),但是我無法獲得Gson Converter軟件包。我從谷歌安裝了gson.jar,但在這些庫中沒有任何地方有一個名爲「GsonConverterFactory」的類,這是我需要解析JSON的。

編輯:我在Windows上。

回答

16

如果您使用的是改造2,則需要包含convert-gson包。對於gradle版本,您可以將compile 'com.squareup.retrofit:converter-gson:2.0.0-beta3'添加到您的依賴項部分。

對於其他構建系統或下載jar,請查看Maven Central convert-gson頁面。

18

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'添加到您的build.gradle文件中並獲取解決的依賴關係或將相應的jar添加到您的bulid路徑。

然後使用GsonConverterFactory.create()得到Converter Factory

我嘗試使用2.0.0-beta1但下面給出它給了我廠的非法類型轉換錯誤,所以搬到2.0.0-beta2

error: method addConverterFactory in class Builder cannot be applied to given types; 
    required: Factory 
    found: GsonConverterFactory 
    reason: actual argument GsonConverterFactory cannot be converted to Factory by method invocation conversion 

所以我的建議是使用2.0.0-beta2

我的build.gradle具有以下依賴項來解決翻新問題。

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' 
+1

iagreen的答案不適用於改造beta2 ..如果使用retrofit2,我們需要使用converter-gson beta 2,如@manoj所述.. – DJphy

+0

得到錯誤 - 未能解決 - 對於上述依賴關係 – NarendraJi

11

在你的模塊試試這個

/* JSON */ 
compile 'com.google.code.gson:gson:2.5' 
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' 

// >Retrofit & OkHttp 
compile ('com.squareup.retrofit2:retrofit:2.0.0-beta3') { 
    // exclude Retrofit’s OkHttp peer-dependency module and define your own module import 
    exclude module: 'okhttp' 
} 
compile 'com.squareup.okhttp3:okhttp:3.0.1' 
8

:應用的build.gradle添加

compile 'com.squareup.retrofit2:converter-gson:[retrofit2 version]' 

以上的版本是一樣與你retrofit2版本,因此,例如您的retrofit2版本是2.1 .0,比你的build.gradle應該是這樣的:

compile 'com.squareup.retrofit2:retrofit:2.1.0' 
compile 'com.squareup.retrofit2:converter-gson:2.1.0'