【问题标题】:Android Retrofit on Kotlin how i can add timestamp to response?Kotlin 上的 Android Retrofit 如何为响应添加时间戳?
【发布时间】:2020-09-06 03:17:01
【问题描述】:

我有一个简单的 Json 类,可以完美地处理改造。 但是里面没有时间戳。 我添加了不在 json 中的自定义字段,但它始终为空

//Custom field for timestamp
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())


//My class for JSON respons 
@Entity(tableName = "nal")
data class CurrencyItem(

@PrimaryKey(autoGenerate = true)
val id:Long,

@SerializedName("base_ccy")
var baseCcy: String,
@SerializedName("buy")
val buy: String,
@SerializedName("ccy")
val ccy: String,
@SerializedName("sale")
val sale: String,

val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
)

【问题讨论】:

  • @Transient 获取时间戳?
  • 我得到的是json中的汇率但是里面没有写时间,我需要在响应模型类中添加时间才能知道最新的更新时间
  • a) 自定义反序列化器或 b) 删除数据类并使用常规类,并将时间戳初始化放在 init 块中
  • 谢谢!反序列化器看起来不错,但我找不到 kotlin retrofit2 的正常示例,仅限 java。
  • 我看到你已经发布了一个关于自定义反序列化器的问题,所以你正在研究这个问题,很酷,然后不会在这里展开,除了说自定义反序列化器实际上是要走的路在这里(所以我上面的选项 b 是错误的) - 改造不会运行 init 块,因此更改为常规课程将无济于事。但还有另一种选择 - 为每个参数分配所有默认值,然后您的时间戳将起作用。它丑陋,你不太可能想要它,但只是指出另一个选择

标签: android json kotlin retrofit response


【解决方案1】:

最简单的解决方案是在模型中为时间戳添加自定义字段。

val timeStamp: String

当改造响应到来时,用时间戳重写这个空字段,我使用方法 SimpleDateFormat

// retrofit response
var res  = resp.body()

// new list which i create and rewrite with timestamp and then return
var l = ArrayList<CurrencyItem>()

//read response list with json converted data
for (r in res.orEmpty()){
   l.add(CurrencyItem(1 ,
                    r.baseCcy,
                    r.buy,
                    r.ccy,
                    r.sale,
                    SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())))
 }

 //return this new list with timestamp. I use repository pattern with livedata
 response.value = l

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2017-11-07
    • 2020-04-26
    • 2020-09-18
    • 2021-11-22
    • 2021-10-06
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多