Akka Http - "Type mismatch" while parsing DateTime into json

426 Views Asked by At

I have created simple trait which should convert models into json:

trait Protocols extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val travelFormat = jsonFormat4(Travel)
}

I have a Travel model which looks like:

case class Travel(id: Option[Long] = None,
                  startDate: DateTime,
                  endDate: DateTime,
                  name: String,
                  description: String,
                  amount: BigDecimal)

But the problem is (as I found out) in DateTime class. In this code I get a compiler error on jsonFormat4 method:

Type mismatch, expected: (NotInferedP1, NotInferedP2, NotInferedP3, NotInferedP4) => NotInferedT, actual: (Option[Long], DateTime, DateTime, String, String, BigDecimal) => Travel

When I remove all DateTime fields it works well. But in my case, I need this fields. So how shoud I fix it? I tried give a default parameter to them, but it also did not work.

1

There are 1 best solutions below

2
joesan On

Could you try writing a custom formatter like this for example:

 implicit val travelFormat: Format[Travel] =
    new Format[Travel] {
       for {
          id <- (json \ "id").validate[Int]
          startDate <- (json \ "startDate").validate[FiniteDuration]
          endDate <- (json \ "endDate").validate[FiniteDuration]
          ....
        } yield {
          Travel(
            id = id,
            startDate = startDate,
            endDate = endDate,
            ....
          )
        }
    }

I'm using the play-json library in the above example!