簡體   English   中英

如何在RetroFit中使用Gson轉換器?

[英]How do I use the Gson converter in RetroFit?

我正在制作一個簡單的RetroFit應用程序用於教育目的,並使用IntelliJ IDEA作為我的IDE。

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

編輯:我在Windows上。

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

然后使用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'

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

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

試試這個

/* 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'

在您的模塊中:app build.gradle add

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM