It's possible to have a class that looks like so:
case class Amount(value: Int)
case class Data(insurance: Option[Amount], itemPrice: Amount)
If insurance = None
it should get a default value of waived: true
E.g:
Data(Some(123),100).asJson
// output
{
"insurance": {
"value": 123
},
"price": 100
}
And when no Insurance is opted for:
Data(None,100).asJson
// output
{
"insurance": {
"waived: true
},
"price": 100
}
How can this fine-grained control be achieved? I tried various tricks with forProduct2
and mapJsonObject
but couldn't get it to behave right:
implicit val testEncoder = deriveEncoder[Option[Amount]].mapJsonObject(j => {
val x = j("Some") match {
case Some(s) => // need to convert to [amount -> "value"]
case None => JsonObject.apply(("waived",Json.fromBoolean(true)))
}
x
})
This can easily get me the waived:true
part but no idea how to handle the Some(s)
case.