Retrofit2 + SimpleXML日期变换器

时间:2018-03-22 16:31:02

标签: kotlin retrofit2 simpledateformat simple-framework

我想在我的simplexml改装转换器中添加一个新的日期格式,根据: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转换器中,如果有的话,会喜欢你们的一些意见!

谢谢!

1 个答案:

答案 0 :(得分:0)

根据您链接的答案,您可以通过向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()
}