I am using Circe for json operations. I have added custom encoders and decoders to handle some of the types, like Joda Time.
While parsing DateTime, I want to allow multiple formats to be passed.
For eg. dd-MM-yyyy'T'HH:mm:ss'Z'
and dd-MM-yyyy'T'HH:mm:ss.SSS'Z'
I have defined my decoder like below:
val dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val dateTimeFormatWithMillis = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
implicit val jodaDateTimeFormat: Encoder[DateTime] with Decoder[DateTime] = new Encoder[DateTime] with Decoder[DateTime] {
override def apply(a: DateTime): Json = Encoder.encodeString(a.toString("yyyy-MM-dd'T'HH:mm:ss'Z'"))
override def apply(c: HCursor): Result[DateTime] = Decoder.decodeString.map { x =>
DateTime.parse(x, dateTimeFormat)
}.apply(c)
}
Now if i input a datetime string matching the dateTimeFormat
, then the decoding will work, but if I pass the datetime in dateTimeFormatWithMillis
, it will fail to process.
I know that I can use the DateTimeFormatterBuilder
to add multiple parsers and process it, however, I was wondering if there is a way in Circe to chain multiple decoders to try one after another until it succeeds or reached end of chain?