我的用例要求我获取如下格式的XML,并需要将其映射到JSON对象:
<settings>
<client ip="......" lat="...." lon="...." isp="...." country="...."/>
<translation lang="xml"> </translation>
</settings>
我使用Retrofit与Moshi作为转换器工厂的请求:
Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi).asLenient())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
我尝试在SimpleXml的帮助下创建响应模型(com.squareup.retrofit2:converter-simplexml:2.9.0)但到目前为止还没有运气。我一直得到这个错误:
com.squareup.moshi。JsonDataException:期望的BEGIN_OBJECT,但在路径$
是STRING
任何人可能有一个想法如何将这个结构映射到Json?提前感谢!
反应模型:
@Root(name = "settings", strict = false)
data class ConfigurationEntity(
@field:Attribute(name = "client", required = false)
@param:Attribute(name = "client", required = false)
val client: ClientEntity?
)
@Root(name = "client")
data class ClientEntity(
@field:Attribute(name = "ip", required = false)
@param:Attribute(name = "ip", required = false)
val ip: String?,
@field:Attribute(name = "lat", required = false)
@param:Attribute(name = "lat", required = false)
val lat: String?,
@field:Attribute(name = "lon", required = false)
@param:Attribute(name = "lon", required = false)
val lon: String?,
@field:Attribute(name = "isp", required = false)
@param:Attribute(name = "isp", required = false)
val isp: String?,
@field:Attribute(name = "country", required = false)
@param:Attribute(name = "country", required = false)
val country: String?
)
<<p>解决方案/strong>改造施工:
Retrofit.Builder()
.addConverterFactory(SimpleXmlConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
模型:
@Root(name = "settings", strict = false)
class ConfigurationEntity {
@field:Element(required = false)
lateinit var client: ClientEntity
}
@Root(name = "client", strict = false)
class ClientEntity {
@field:Attribute
lateinit var ip: String
@field:Attribute
lateinit var lat: String
@field:Attribute
lateinit var lon: String
@field:Attribute
lateinit var isp: String
@field:Attribute
lateinit var country: String
}
这个链接也可能是有用的Kotlin -解析Xml响应与列表使用SimpleXml
您需要将此转换器工厂添加到您的Retrofit Builder -
Retrofit.Builder()
.addConverterFactory(SimpleXmlConverterFactory.create())
这允许Retrofit解释它正在获取的XML,并将其转换为等效的JSON数据对象。