Kotlin 上的安卓改造如何在响应中添加时间戳?



我有一个简单的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())
)

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

val timeStamp: String

当改造响应到来时,用时间戳重写这个空字段,我使用方法 简单日期格式

// 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

最新更新