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:注释@ org.simpleframework.xml.Element(数据= false,名称=,required = true,type = void)必须标记一个设置或获取方法
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数据
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<result code="0">Success</result>
<token>XXXXXXXXXXXXXXXXXXXX</token>
<uid>4294967295</uid>
</response>
科特林模型对象在下面
@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.
推荐答案
This is the same problem as: kotlin data class + bean validation 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屋!