I have a value class that accepts an Either
, which I would like to generate a Play for Scala v2.5.6 JSON Format
for:
import org.joda.time.{DateTime, Duration}
case class When(when: Either[DateTime, Duration]) extends AnyVal
I think I have the writes
method figured out; the problems I am having are with the reads
method. I've attempted two approaches, both failed for different reasons.
Attempt #1, showing both the reads
and writes
methods:
import play.api.libs.json._
import play.api.libs.json.Json.obj
object When {
def apply(dateTime: DateTime): When = When(Left(dateTime))
def apply(duration: Duration): When = When(Right(duration))
implicit val whenFormat = new Format[When] {
def reads(json: JsValue): JsResult[When] = {
val reads = (__ \ "dateTime").read[Long] { (millis: Long) =>
When(Left(new DateTime(millis)))
} | (__ \ "duration").read[Long] { (millis: Long) =>
When(Right(new Duration(millis)))
}
reads.reads(json)
}
def writes(o: When): JsValue = obj(
o.when.fold(
duration => "duration" -> duration.getMillis,
dateTime => "dateTime" -> dateTime.getMillis
)
)
}
}
The error messages are:
overloaded method value read with alternatives:
[error] (t: Long)play.api.libs.json.Reads[Long] <and>
[error] (implicit r: play.api.libs.json.Reads[Long])play.api.libs.json.Reads[Long]
[error] cannot be applied to (Long => When)
[error] val reads = (__ \ "dateTime").read[Long] { (millis: Long) =>
[error] overloaded method value read with alternatives:
[error] (t: Long)play.api.libs.json.Reads[Long] <and>
[error] (implicit r: play.api.libs.json.Reads[Long])play.api.libs.json.Reads[Long]
[error] cannot be applied to (Long => When)
[error] } | (__ \ "duration").read[Long] { (millis: Long) =>
Attempt #2, just showing the reads
method:
def reads(json: JsValue): JsResult[When] =
JsSuccess(
When(Left(new DateTime((__ \ "dateTime").read[Long]))) ||
When(Right(new Duration((__ \ "duration").read[Long])))
)
The error message is:
value || is not a member of When
[error] Note: implicit value whenFormat is not applicable here because it comes after the application point and it lacks an explicit result type
[error] Error occurred in an application involving default arguments.
I'd just like something that works, and I don't care what approach is used (even one I did not show), so long as it is maintainable and efficient. It would also be helpful to know what was wrong with each of these approaches.
extends AnyVal
fromWhen
extends AnyVal
made no difference to either approach