I defined a case class Fruit:
case class Fruit(name: String, weight: Double)
I wrote an action to save a fruit
def saveFruit = Action(parse.json) { request: Request[JsValue] =>
import models.Implicits._
val json = request.body
val fruitResult = Json.fromJson[Fruit](json)
if (fruitResult.isSuccess) {
val fruit = fruitResult.get
println(fruit)
Ok(JsString("1"))
} else {
Ok(JsString("2"))
}
}
If the request body is { "name":"ABC","weight":10}, then the action will be successfully called.
If the request body is { "name":"ABC"},then an error occurs,complaining that the weight is not undefined on object
{ "name":"ABC"} is a valid json string that can't parsed as a Fruit and weight will be null
I am not sure how to fix this issue.
I am using Play 2.6.0
Fruitto use optional values?name: Option[String], weight: Option[Double]?