3

I need to serialize ArrayList as data class variable with custom DateSerializer, with single date variable i use annotation:

@Serializable
      data class SearchBundle(
      @Serializable(with = DateSerializer::class) var startDate: Date? = null)

Somebody know how to do it for arrayList of dates?

Webdma
  • 714
  • 6
  • 16

2 Answers2

7

Probably easier then your current approach is to just specify the DateSerializer on file level of your SearchBundle-class via UseSerializers-annotation, e.g.:

@file:UseSerializers(DateSerializer::class)

import kotlinx.serialization.*
import java.util.*

@Serializable
data class SearchBundle(
        var startDate: List<Date>? = null)

That way you can keep your DateSerializer as is and the rest of your code just works, i.e. it will automatically use DateSerializer for all Date-types within that file.

Roland
  • 22,259
  • 4
  • 57
  • 84
  • An interesting solution, I did not know that you can assign a serializer at the file level, i will try, thanks. – Webdma Feb 26 '19 at 17:10
1
@Serializable
class TestDates(
    @Optional @Serializable(with = DatesArraySerializer::class) var dates: ArrayList<Date>? = null
)

object DatesArraySerializer : KSerializer<ArrayList<Date>> {

    override val descriptor = ArrayClassDesc(DateSerializer.descriptor)

    override fun serialize(encoder: Encoder, obj: ArrayList<Date>) {
        encoder.encodeSerializableValue(ArrayListSerializer(DateSerializer), obj)
    }

    override fun deserialize(decoder: Decoder): ArrayList<Date> {
        val dates = decoder.decodeSerializableValue(ArrayListSerializer(DateSerializer))

        return dates.toList() as ArrayList<Date>
    }
}
Webdma
  • 714
  • 6
  • 16