Android - 解析 XML JSON

Android - Parse XML to JSON

我的用例要求我获取格式如下的 XML 并需要将其映射到 JSON 对象:

<settings>
<client ip="......" lat="...." lon="...." isp="...." country="...."/>
<translation lang="xml"> </translation>
</settings>

我正在使用 Moshi 的 Retrofit 作为转换器工厂来满足以下要求:

       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: Expected BEGIN_OBJECT but was STRING at path $

任何人都可能知道如何将此结构映射到 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?
)

解决方案

改装建造者:

       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
}

另外这个link可能会有帮助Kotlin - parsing Xml response with list using SimpleXml

您需要将此转换器工厂添加到您的 Retrofit Builder -

Retrofit.Builder()
.addConverterFactory(SimpleXmlConverterFactory.create())

这允许 Retrofit 解释它正在获取的 XML 以转换为等效的 JSON 数据对象。