4

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.

2

1 Answer 1

1

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!

2
  • It is an option. But does Akka has any user friendly auto formatter? I really need to write own formatter to parse dates?
    – Developus
    Dec 23, 2018 at 19:45
  • I tried to use your code, but I got an compiler error: Too many arguments for method parameters(ToResponseMarshallable)
    – Developus
    Dec 23, 2018 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.