JSON deserializer for Anorm
The JSON serializer/deserializer supports all the basic values that are covered by the JSON specification. If you want to serialize a custom type you have to tell the serializer how to do that.
Play's JSON serializer uses a Scala (originally Haskell) pattern called type class. In a nutshell, it allows polymorphism without subclassing. This is achieved by bringing an implicit value in scope, i.e. to handle a new type, you define an implicit value/method/object. In your concrete example, you define a type class instance for Pk[Int]
.
You could convert the Pk[Int]
manually in your code, or as in many other frameworks implement the conversion in the Pk
class directly, but the type class approach is cleaner (because JSON conversion is a separate concern) and easier to reuse (now you can convert a Pk[Int]
anywhere you want even if the Pk
class itself doesn't support it, imagine extending a closed-source system).
As to your code, it should just work fine, just make sure you have the necessary imports in scope:
import play.api.libs.json._import play.api.libs.json.util._import play.api.libs.json.Writes._import play.api.libs.functional.syntax._