How to deserialize json to sealed trait using playframework in scala? -
i'm new in scala , got stuck in object deserialization. appreciate help.
so problem is, have sealed trait permission
, case objects extend it:
sealed trait permission case object administrator extends permission case object dispatcher extends permission case object editor extends permission case object normaluser extends permission object permission { def valueof(value: string): permission = value match { case "administrator" => administrator case "dispatcher" => dispatcher case "editor" => editor case "normaluser" => normaluser case _ => throw new illegalargumentexception() } def stringvalueof(value: permission): string = value match { case administrator => "administrator" case dispatcher => "dispatcher" case editor => "editor" case normaluser => "normaluser" case _ => throw new illegalargumentexception() } }
and have user
case class permission
:
case class user(id: option[int], username: string, permission: permission, firstname: option[string]=none, lastname: option[string]=none)
i've created json.reads[permission]
, json.reads[user]
, whenever run code, no unapply function found
exception. i've tried search same issue, didn't anything. please solve issue. thx.
using scala 2.11.x , playframework
play can automatically figure out json reader case classes. in case have define reader permission
manually:
implicit val permissionreads: reads[permission] = __.read[string].map(permission.valueof)
this throw actual exception in case of problems permission format, instead of returning jserror
. fix can use collect
:
implicit val permissionreads: reads[permission] = __.read[string].collect(validationerror("unsupported permission format"))( function.unlift(s => scala.util.try(permission.valueof(s)).tooption))
if don't want long incantation function.unlift(s => scala.util.try(permission.valueof(s)).tooption
can reduce replacing valueof
(or adding new function object permission
) partialfunction[string, permission]
or function returning option[permission]
instead of throwing error.
Comments
Post a Comment