0

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

2
  • looks like you want Fruit to use optional values? name: Option[String], weight: Option[Double]? Commented Jul 20, 2017 at 15:48
  • Thanks @tgk for the answer. I got another question stackoverflow.com/questions/45187140/…, could you please take a look? Commented Jul 20, 2017 at 22:57

1 Answer 1

1

I strongly suggest not going down the rabbit hole of allowing null anywhere. If you start allowing this in your request objects, you will never know whether there's a null anywhere in your models.

The typical way to approach this is to set this to Option as was suggested in the comments.

If you're working on a more elaborate solution, it might make sense to create dedicated request objects with lots of Options for values where the client might not send a value. You would then map/transform the request objects into your domain model in the controller and validate the input accordingly.

For example:

case class FruitRQ(name: String, weight: Option[Double])

case class Fuit(name: String, weight: Double)

class MyController {

  def myAction = {
    val fruitRq = Json.fromJson[FruiteRQ](request.body)
    (for (weight <- fruitRq.weight) yield {
      val fruit = Fruit(fruitRq.name, weight)
      // do something with the validate fruit
    }).getOrElse {
      // return 4xx to client saying that a field is missing
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @rethab for the answer. I got another question stackoverflow.com/questions/45187140/…, could you please take a look?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.