g71*_*132 1 java xml android kotlin kotlin-android-extensions
我有这样的xml:
<horo>
<aries>
<today>
??????? ??? ????? ??????? ????????. ???? ?? ???????????? ??? ?????? ??????? ?? ???, ?????? ???????? ?????? ? ???????? ????????? ??????? ???????.
</today>
</aries>
<taurus>
<today>
??????? ? ??? ????? ?????????? ???????? ?? ?????? ??????. ?????? ??? ?? ??????????? ????????? ?? ? ??? ????? ?????, ???????????? ? ? ?????? ??????? ??????????? ?????? ? ????????.
</today>
</taurus>
</horo>
Run Code Online (Sandbox Code Playgroud)
现在我学习kotlin whith改造.我包含解析xml的库,而不是我无法理解如何解析这个xml的create对象.我有对象:
@Root(name = "horo", strict = false)
open class DailyHoroscope{
@get : Element(name = "aries") var aries : Aries? = null
}
@Root(name = "aries", strict = false)
open class Aries{
@get : Element(name = "today") var today : String? = null
}
Run Code Online (Sandbox Code Playgroud)
但我有错误:
rg.simpleframework.xml.core.ConstructorException:默认构造函数不能在类ac中的方法'aries'上接受只读@ org.simpleframework.xml.Element(data = false,name = aries,required = true,type = void) .kotlintest.model.
UPD
我在java中编写代码:
@Root(name = "horo", strict = false)
public class DailyHoroscopeJ {
@Element(name = "aries")
public Aries aries;
public Aries getAries() {
return aries;
}
public void setAries(Aries aries) {
this.aries = aries;
}
}
@Root(name = "aries", strict = false)
class Aries{
@Element(name = "today")
public String today;
public String getToday() {
return today;
}
public void setToday(String today) {
this.today = today;
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,然后我转换为kotlin
@Root(name = "horo", strict = false)
class DailyHoroscope {
@get:Element(name = "aries")
var aries:Aries? = null
}
@Root(name = "aries", strict = false) class Aries {
@get:Element(name = "today")
var today:String? = null
}
Run Code Online (Sandbox Code Playgroud)
但我有同样的问题((((
实际上,Simple XML Framework在Kotlin属性方面存在一些问题,让事情发挥作用可能有点棘手.
说实话,我不太确定你的具体情况是什么问题,但我猜不应该为getter指定注释,而是为字段指定.
无论如何,我正在以这种方式组合Simple XML和Kotlin数据类,它似乎工作得很好:)
data class Section (
@field:Element(name = "id", required = false)
@param:Element(name = "id", required = false)
val id: Long? = null,
@field:Attribute(name = "title", required = false)
@param:Attribute(name = "title", required = false)
val title: String? = null
)
Run Code Online (Sandbox Code Playgroud)
编辑:如果你不想使用数据类(我强烈推荐,但你可能有原因),这应该没有"数据"关键字就好了.如果您不想创建构造函数,只需将属性声明直接移动到类中并删除@param注释(@field必须保留).
@daementus的答案几乎是完美的.如果要使用带有默认参数的构造函数注入,则必须强制Kotlin生成构造函数重载:
data class Section @JvmOverloads constructor(
@field:Element(name = "id")
@param:Element(name = "id")
val id: Long,
@field:Attribute(name = "title", required = false)
@param:Attribute(name = "title", required = false)
val title: String = ""
)
Run Code Online (Sandbox Code Playgroud)
如果没有它,您将获得与类Section不匹配的构造函数.默认情况下,Kotlin会生成一个包含所有参数和特殊构造函数的构造函数.
注意:我更愿意在评论中回答,但我没有足够的积分.
| 归档时间: |
|
| 查看次数: |
4823 次 |
| 最近记录: |