I am trying to parse a request in Scala
For example, I have this case class
case class User(
id: Option[Long] = None,
name: Option[String] = None,
email: Option[String] = None,
firstname: Option[String] = None,
lastname: Option[String] = None,
isActive: Boolean = true
)
object User {
implicit val User = Json.format[User]
}
I have two endpoints one for create and one for update
In the create endpoint I only want to send name and email. In the update endpoint the id will be in the path and all the other fields are optional or have a default value.
The controllers receive the requests and parse the data like this
def post: Action[JsValue] = Action.async(parse.json) { implicit request =>
request.body.validate[User].fold(
...
}
The problem is that when the controller validates the json body, it does not add the optional fields with the default values.
I tried adding something like this
object User {
implicit def jsonFormat = Json.using[Json.WithDefaultValues].format[User]
}
But it did not change anything
Reads) and put the default values in there. - LasfOption[type]it will automatically returnNoneif no value or not found so default valueNoneis useless. - Rex