gpt4 book ai didi

kotlin - Retrofit2 + SimpleXML日期转换器

转载 作者:行者123 更新时间:2023-12-02 13:38:41 26 4
gpt4 key购买 nike

我想向我的simplexml retrofit 转换器添加新的日期格式,如下所示:Parse date with SimpleFramework

class DateTransformer(format: String) : Transform<Date> {
private val formatter = SimpleDateFormat(format) // SimpleDateFormat is not thread safe!
@Throws(Exception::class)
override fun read(value: String): Date {
return formatter.parse(value)
}

@Throws(Exception::class)
override fun write(value: Date): String {
return formatter.format(value)
}
}

我不确定如何将其集成到Retrofit转换器中,如果有的话,是否会喜欢你们提供的一些信息!

谢谢 !

最佳答案

根据您链接的答案,可以通过向RegistryMatcher提供Serializer来使SimpleXML解析日期。

另外,Retrofit的SimpleXml转换器允许您将Serializer传递给SimpleXmlConverterFactory

编辑:
这是完整的(基础)示例。

import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import org.simpleframework.xml.core.Persister
import org.simpleframework.xml.transform.RegistryMatcher
import org.simpleframework.xml.transform.Transform
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
import retrofit2.http.GET
import java.text.SimpleDateFormat
import java.util.*

fun main(args: Array<String>) {
val matcher = RegistryMatcher()
val format = SimpleDateFormat("yyyy-MM-dd")
matcher.bind(Date::class.java, DateTransformer(format))
val serializer = Persister(matcher)

val fakeHttpClient = createFakeHttpClient()
val retrofit = Retrofit.Builder()
.client(fakeHttpClient)
.addConverterFactory(SimpleXmlConverterFactory.create(serializer))
.baseUrl("http://localhost/")
.build()

val api = retrofit.create(MyFakeApi::class.java)
val myData = api.callApi().execute().body()

println(myData)
}

private fun createFakeHttpClient() = OkHttpClient.Builder()
.addInterceptor(FakeInterceptor())
.build()

class DateTransformer(private val format: SimpleDateFormat) : Transform<Date> {

override fun write(value: Date?): String {
return format.format(value)
}

override fun read(value: String?): Date {
return format.parse(value)
}

}

data class MyData @JvmOverloads constructor(var date: Date? = null, var title: String = "")

interface MyFakeApi {
@GET("foo")
fun callApi(): Call<MyData>
}

class FakeInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain?) = Response.Builder()
.request(Request.Builder()
.url("http://localhost")
.build())
.code(200)
.body(ResponseBody.create(MediaType.parse("application/xml"), """
<response>
<date>2018-03-22</date>
<title>Fake title</title>
</response>
"""))
.protocol(Protocol.HTTP_1_1)
.message("")
.build()
}

关于kotlin - Retrofit2 + SimpleXML日期转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com