在Kotlin中使用SimpleXML序列化改造xml响应

时间:2019-02-26 09:54:09

标签: android kotlin retrofit2 simple-framework

我正在尝试使用SimpleXML将改造的xml响应序列化为一个对象。

但是,发生以下异常:

  

org.simpleframework.xml.core.ValueRequiredException:无法满足@ org.simpleframework.xml.ElementList(data = false,empty = true,entry =,inline = true,name = ALLFile,required = true ,在字段“文件”上输入type = void)

回复示例:

<LIST> 
   <ALLFile>
      <File>
         <NAME>SOME FILE NAME</NAME>
         <FPATH>SOME FILE PATH</FPATH>
         <SIZE>160053622</SIZE>
         <TIMECODE>1299673239</TIMECODE>
         <TIME>2018/11/23 14:04:46</TIME>
         <ATTR>33</ATTR>
      </File>
   </ALLFile>
   <ALLFile> 
      <File> 
	 <NAME>SOME FILE NAME</NAME>
         <FPATH>SOME FILE PATH</FPATH>
         <SIZE>160053622</SIZE>
         <TIMECODE>1299673559</TIMECODE>
         <TIME>2018/11/23 14:14:46</TIME>
         <ATTR>33</ATTR>
      </File>
   </ALLFile>
</LIST>

对象:

@Root(name = "LIST", strict = false)
data class ListResponse @JvmOverloads constructor(
    @field:ElementList(name = "ALLFile", inline = true) var files: List<GetVideosResponse>? = null
)

@Root(strict = false, name = "File")
data class GetVideosResponse @JvmOverloads constructor(
    @field:Element(name = "NAME", required = false) var name: String? = null,
    @field:Element(name = "FPATH", required = false) var fPath: String? = null,
    @field:Element(name = "SIZE", required = false) var size: Int? = null,
    @field:Element(name = "TIMECODE", required = false) var timeCode: Long? = null,
    @field:Element(name = "TIME", required = false) var time: String? = null,
    @field:Element(name = "ATTR", required = false) var attr: Int? = null)

我从服务器收到200响应,因此可以排除我的请求逻辑问题。这使我相信问题在于序列化对象,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

找到了解决方法,不一定是答案,但对我有用...

我将 XML 响应作为字符串,将其转换为 JSON ,然后使用我通常的JSON序列化库( moshi )来序列化JSON转换为对象。

private fun parseXmlToJsonObject(xml: String) : String {
    var jsonObj: JSONObject? = null
    try {
        jsonObj = XML.toJSONObject(xml)
    } catch (e: JSONException) {
        Log.e("JSON exception", e.message)
        e.printStackTrace()
    }

    return jsonObj.toString()
}

fun<T> parseResponse(xml: String, clazz: Class<T>) : T {
    try {
        return initializeMoshi().adapter(clazz).fromJson(parseXmlToJsonObject(xml))!!
    }catch (e: IOException){
        throw IllegalArgumentException("Could not deserialize: $xml into class: $clazz")
    }
}

private fun initializeMoshi(): Moshi {
    return Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
}

并这样称呼它:

val myObject = parseResponse(response.body()!!.string(), MyJsonClass::class.java)