最近,我有一个任务来处理xml格式的答案。我试图使用改造和SimpleXmlConverterFactory解决问题。请告诉我如何解决该问题或使用哪种替代方法。
class App : Application() {
lateinit var api : Api
override fun onCreate() {
super.onCreate()
val retrofit = Retrofit.Builder()
.baseUrl("http://www.nbrb.by/Services/")
.addConverterFactory(SimpleXmlConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
api = retrofit.create(Api::class.java)
}
}
@Root(name="DailyExRates")
class Сurrency (@ElementList val currencyItems: List<CurrencyItem>)
@Element(name="Currency")
class CurrencyItem (@Element(name="NumCode") val numCode: Int,
@Element(name="CharCode") val charCode: String,
@Element(name="Scale") val scale: Int,
@Element(name="Name") val name: String,
@Element(name="Rate") val rate: Double)
interface Api {
@GET("XmlExRates.aspx?ondate=4.5.2019")
fun getCurrency() : Observable<Call<Currency>>
}
and my dependencies
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation ('com.squareup.retrofit2:converter-simplexml:2.5.0', {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
})
答案 0 :(得分:0)
这是代码的固定版本。
@Root(name = "DailyExRates")
class СurrencyModel @JvmOverloads constructor (){
@get:Attribute(name = "Date")
@set:Attribute(name = "Date")
var date: String? = null
@get:ElementList(name="Currency", inline=true)
@set:ElementList(name="Currency", inline=true)
var currencyItems: List<CurrencyItem>? = null
}
@Root(name = "Currency")
class CurrencyItem @JvmOverloads constructor (){
@get:Attribute(name = "Id")
@set:Attribute(name = "Id")
var id: Short? = null
@set:Element(name = "NumCode")
@get:Element(name = "NumCode")
var numCode: Int? = null
@set:Element(name = "CharCode")
@get:Element(name = "CharCode")
var charCode: String? = null
@set:Element(name = "Scale")
@get:Element(name = "Scale")
var scale: Int? = null
@set:Element(name = "Name")
@get:Element(name = "Name")
var name: String? = null
@set:Element(name = "Rate")
@get:Element(name = "Rate")
var rate: Double? = null
}
interface Api {
@GET("XmlExRates.aspx?ondate=4.5.2019")
fun getCurrency() : Observable<СurrencyModel>
}
val retrofit = Retrofit.Builder()
.baseUrl("http://www.nbrb.by/Services/")
.addConverterFactory(SimpleXmlConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
api = retrofit.create(Api::class.java)
val api = (application as App).api
api.getCurrency()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ onLoaded(it) },{ onError(it) })
我的依存关系保持不变。 它可能看起来很怪异,但是有效。从我获得信息的链接: http://www.nbrb.by/Services/XmlExRates.aspx?ondate=4.5.2019