Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Scala JSON body parser default value field

Hello I'm having trouble with a JSON body parser. My problem is the following I have a case class with some optional parameters (Option[T]) and a parameter with a default value which I do not want to be typed as Option[T].

However when parsing a JSON body having the field with the default value omitted I get an error

play.api.libs.JsError
/count error path missing

Here is my controller code :

object MyController extends Controller{


  implicit val itemWrites = Json.writes[Item]
  implicit val itemReads = Json.reads[Item]
  implicit val itemFormats = Json.format[Item]

  def add = DBAction(parse.json){ implicit rs =>

    val item =  rs.request.body.validate[Item]
}

Here is my case class :

case class Item( id:Option[Int], name:String, description:Option[String], count:Int=0)

Any chance I can achieve the same behavior as Option[T] with the default value field?

Thanks

I'm using :

  • Scala 2.10
  • Play Framework 2.2.1
  • Play-Slick plugin 0.5.0.8
like image 447
ufasoli Avatar asked Dec 17 '13 08:12

ufasoli


1 Answers

Almost. You can define a default value with an Option like this:

case class Item( description:Option[String] = Some("String"))

If you definitely do not want an option, you can have a look here:

Defaults for missing properties in play 2 JSON formats

like image 126
Maxime Dantec Avatar answered Oct 04 '22 02:10

Maxime Dantec