我想通过在Kotlin中使用Retrofit2+SimpleXML从API获取XML数据,并将其映射到Kotlin模型对象.

However, I got such as the following error message from SimpleXML.

org.simpleframework.xml.core.MethodException: Annotation @org.simpleframework.xml.Element(data=false, name=, required=true, type=void) must mark a set or get method

This is fetched XML data

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
    <result code="0">Success</result>
    <token>XXXXXXXXXXXXXXXXXXXX</token>
    <uid>4294967295</uid>
</response>

Kotlin model object is below

@Root(name = "response")
public class User() {
    @Element public var result: String? = null
    @Element public var token: String? = null
    @Element public var uid: String? = null
}

APIClient如下所示.

interface  MyService {
    @GET("/testLogin.xml")
    fun getUser(): Call<User>
}

val retrofit = Retrofit.Builder()
        .baseUrl(baseURL)
        .addConverterFactory(SimpleXmlConverterFactory.create())
        .build()
val call = retrofit.create(MyService::class.java).getUser()
call.enqueue(object: Callback<User> {
        override fun onResponse(p0: Call<User>?, response: Response<User>?) {
            val response = response?.body()
        }
        override fun onFailure(p0: Call<User>?, t: Throwable?) {
            Log.e("APIClient", t?.message)
        }

我得到了HTTP状态码200和正确的XML数据.所以我认为我对模型对象的声明是个问题.

推荐答案

This is the same problem as: 100

您需要使用Annotation use-site targets,因为属性上注释的默认优先级为:

  • parameter (if declared in constructor)
  • property (if the target site allows, but only Kotlin created annotations can do this)
  • field (likely what happened here, which isn't what you wanted).

使用getset目标将注释放置在getter或setter上.这是给Getters 的:

@Root(name = "response")
public class User() {
    @get:Element public var result: String? = null
    @get:Element public var token: String? = null
    @get:Element public var uid: String? = null
}

有关详细信息,请参阅linked answer.

Kotlin相关问答推荐

最好的方法来创建一个 map 在kotlin从两个列表

我需要后台工作才能使用卡夫卡的消息吗?

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

合并状态流

如何在 Jetpack Compose 中启动和停止动画

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

Kotlin 中获取类简单名称的最佳实践

如何为 material.Slider 视图创建绑定适配器?

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

在 Kotlin 中取最后 n 个元素

主机名不能为空

无法为 retrofit2.Call 调用无参数构造函数

kotlin-bom 库是做什么的?

Kotlin JVM 和 Kotlin Native 有什么区别?

Tornadofx - 如何在每个实例上将参数传递给 Fragment

Kotlin reflect proguard SmallSortedMap

接口中的属性不能有支持字段

查找是否在列表中找到具有特定属性值的元素

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

Android Studio - java.io.IOException:无法生成 v1 签名