提问人:Purvesh Dodiya 提问时间:11/7/2022 更新时间:11/11/2022 访问量:321
无法使用 retofit 解析对 kotlin 数据类的 xml 响应
Not able to parse xml response to kotlin data class with retofit
问:
我正在尝试调用给我xml响应的rest api。我正在使用 simplexml 转换器工厂的改造将 xml 解析为 kotlin 数据 clas。下面是来自 api 的 xml 响应:
<category>
<api-version>1.0</api-version>
<books>
<list>
<result>
<author>Hello1</author>
<brief>Hii</brief>
</result>
<result>
<author>Hello2</author>
<brief>Hii2</brief>
</result>
</list>
</books>
</category>
下面是我的 Kotlin 数据类
data class CategoryResponseModel(
@field:Element(name = "api-version", required = false)
@param:Element(name = "api-version", required = false)
val apiVersion: String? = null,
@field:Element(name = "books", required = false)
@param:Element(name = "books", required = false)
val books: Books? = null
)
data class Books(
@field:Element(name = "list", required = false)
@param:Element(name = "list", required = false)
val list: BookList? = null
)
@Root(name = "list")
data class BookList(
@field:Element(name = "result", required = false)
@param:Element(name = "result", required = false)
val result: List<BookSearchResult>? = null,
)
data class BookSearchResult(
@field:Element(name = "author", required = false)
@param:Element(name = "author", required = false)
val author: String? = null,
@field:Element(name = "brief", required = false)
@param:Element(name = "brief", required = false)
val briefSynopsis: String? = null,
)
但是我收到改造SimpleXML的错误org.simpleframework.xml.core.ElementException: Element 'result[1]/author[1]' does not have a match in class BookList
答:
8赞
Purvesh Dodiya
11/11/2022
#1
经过这么多的发现和尝试和错误,我得到了解决方案。
我刚刚在块下方的数组列表元素中进行了更改,
@Root(name = "list")
data class BookList(
@field:ElementList(inline = true, required = false)
@param:ElementList(inline = true, required = false)
val result: List<BookSearchResult>? = null,
)
完整的解决方案代码如下。
data class CategoryResponseModel(
@field:Element(name = "api-version", required = false)
@param:Element(name = "api-version", required = false)
val apiVersion: String? = null,
@field:Element(name = "books", required = false)
@param:Element(name = "books", required = false)
val books: Books? = null
)
data class Books(
@field:Element(name = "list", required = false)
@param:Element(name = "list", required = false)
val list: BookList? = null
)
@Root(name = "list")
data class BookList(
@field:ElementList(inline = true, required = false)
@param:ElementList(inline = true, required = false)
val result: List<BookSearchResult>? = null,
)
data class BookSearchResult(
@field:Element(name = "author", required = false)
@param:Element(name = "author", required = false)
val author: String? = null,
@field:Element(name = "brief", required = false)
@param:Element(name = "brief", required = false)
val briefSynopsis: String? = null,
)
评论