Reputation: 4719
I'm using Play 2.3.7, Scala version 2.11.4.
I have this kind of class. I would like to serialize and deserialize object into json and from json to object.
case class Person(var id: Int = 0,
var first_name: String = "",
var last_name: String = "",
var email: String = "",
var date_of_birth: DateTime = new DateTime())
After reading documents I found I need own implicit read and writer. So I tried as follows:
implicit val personWrites: Writes[Person] = (
(__ \ "id").write[Int] ~
(__ \ "first_name").write[String] ~
(__ \ "last_name").write[String] ~
(__ \ "email").write[String] ~
(__ \ "date_of_birth").write[DateTime])
(unlift(Person.unapply))
implicit val userReads: Reads[Person] = (
(__ \ "id").read[Int] ~
(__ \ "first_name").read[String] ~
(__ \ "last_name").read[String] ~
(__ \ "nickname").read[String] ~
(__ \ "date_of_birth").read[DateTime]
)(Person.apply _)
I get compiler error: overloaded method value apply with alternatives ......
Please inform me how to do it? Thanks!
Upvotes: 1
Views: 706
Reputation: 3542
You don't need to write your own reads / writes unless they are not symmetric or you are doing something custom. Json has a format method that creates an formatter from case classes. It also has default formatters for some things including Joda DateTime classes.
implicit val personFormatter:Format[Person] = Json.format[Person]
Upvotes: 2