I have an abstract class which has an annotated property
abstract class DataPoint(
@Json(name="collected_at")
@Iso8601Time
val time: Long
)
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class Iso8601Time
class Iso8601TimeAdapter {
companion object {
val TIME_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
}
@Suppress("unused")
@ToJson
fun toJson(@Iso8601Time time: Long): String {
return TIME_FORMAT.format(time)
}
@Suppress("unused")
@FromJson
@Iso8601Time
fun fromJson(strTime: String): Long {
return TIME_FORMAT.parse(strTime)?.time ?: 0
}
}
Then I have an implementation of this class and a serialization code
class BpDataPoint(
time: Long,
val systolic: Int,
val diastolic: Int)
: DataPoint(time)
val bloodPressure = BpDataPoint(System.currentTimeMillis(), 112, 120)
val m = Moshi.Builder()
.add(Iso8601TimeAdapter())
.add(KotlinJsonAdapterFactory())
.build()
val a = m.adapter(BpDataPoint::class.java)
val json = a.toJson(bloodPressure)
Althougth time
property is marked with another name to serialize moshi ignores this annotation. Also custom adapter for the time
field does not work as well.
This is the json I am getting
{
"time":1620922108339, // I expect here "collected_at": "2021-05-13 19:25"
"systolic":112,
"diastolic":120
}