Reputation: 965
i have a case class signup with an optional variable "secondaryEmail"
case class SignUp(firstNname : String,
var lastName: String,
var email: String,
var secondryEmail : Option[String]
)
i want to convert it to Json for that i have written a function to convert it into a Map
def putInMap(obj: SignUp) = {
val signupMap = Map(
"firstname" -> obj.firstNname,
"lastname" -> obj.lastName,
"email" -> obj.email,
"secondryemail" -> Some(obj.secondryEmail)
)
signupMap
}
Now when i try to convert it to Json like this
val signupjson = Json.toJson(putInMap(SignUp))
it gives me this error
No Json serializer found for type scala.collection.immutable.Map[String,java.io.Serializable]. Try to implement an implicit Writes or Format for this type.
is there any other way of solving this error or i have to implement an implicit Write for this?
Upvotes: 0
Views: 992
Reputation: 391
You don't need to convert it to a map in the first place.
implicit val signupWriter = Json.writes[SignUp]
val up = SignUp("Jo", "B", "foo@mail.com", None)
val json = Json.toJson(up)
And it will output a JsValue
for you.
Upvotes: 0
Reputation: 11532
I thing that you shoul change your code by this:
def putInMap(obj: SignUp) = {
val signupMap = Map(
"firstname" -> obj.firstNname,
"lastname" -> obj.lastName,
"email" -> obj.email,
"secondryemail" -> obj.secondryEmail.getOrElse("")
)
signupMap
}
Use getOrElse to access a value or a default when no value is present: the empty String or what a string of you want,
if not you should try tow write the implicit methods writes for parsing the Json as suggested by play framework documentation in Using Writes converters at this link do not forget to use .writeNullable for the Option[String] field
Upvotes: 2