Kotlin 中的 Retrofit2 + SimpleXML:MethodException:注释必须标记 set 或 get 方法 [英] Retrofit2 + SimpleXML in Kotlin: MethodException: Annotation must mark a set or get method
问题描述
我想通过在 Kotlin 中使用 Retrofit2 + SimpleXML 从 API 获取 XML 数据并将其映射到 Kotlin 模型对象.
I want to fetch XML data from API and map it to Kotlin model object by using Retrofit2 + SimpleXML in Kotlin.
但是,我从 SimpleXML 收到如下错误消息.
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) 必须标记一个 set 或 get 方法
org.simpleframework.xml.core.MethodException: Annotation @org.simpleframework.xml.Element(data=false, name=, required=true, type=void) must mark a set or get method
这是获取的 XML 数据
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 模型对象在下面
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 如下.
and APIClient is as follows.
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 数据.所以我认为我的模型对象声明有问题.
I got HTTP status code 200 and correct XML data. So I think my declaration of model object is problem.
推荐答案
这个问题与:kotlin 数据类 + bean 验证jsr 303
您需要使用注释使用站点目标 因为属性注释的默认优先级为:
You need to use Annotation use-site targets since the default for an annotation on a property is prioritized as:
- 参数(如果在构造函数中声明)
- 属性(如果目标站点允许,但只有 Kotlin 创建的注释可以做到这一点)
- 字段(很可能是这里发生的,这不是您想要的).
- 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).
使用 get
或 set
目标将注解放在 getter 或 setter 上.这是给吸气剂的:
Use get
or set
target to place the annotation on the getter or setter. Here it is for the getter:
@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
}
有关详细信息,请参阅链接答案.
See the linked answer for the details.
这篇关于Kotlin 中的 Retrofit2 + SimpleXML:MethodException:注释必须标记 set 或 get 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!