Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. Let's test custom types for Json serializer
- import play.api.libs.json._
- case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
- // add to routes: GET /json/user/defined controllers.TestController.jsonUserDefined
- def jsonUserDefined = Action {
- val result = LastError(None, 55, Some(new RuntimeException("qwerty")))
- Ok(Json.toJson(result))
- }
- // Compile output:
- // Error:(69, 19) No Json serializer found for type TestController.this.LastError.
- // Try to implement an implicit Writes or Format for this type.
- // Ok(Json.toJson(result))
- // 1.1. Now we add implicit serializer
- case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
- implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
- // Compile output:
- // Error:(65, 62) No instance of play.api.libs.json.Writes is available for scala.Option[java.lang.Exception]
- // in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
- // implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
- // 1.3. so we need to provide extra implicit value to serialize Exception type
- case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
- implicit val exceptionFormat: Format[Exception] = new Format[Exception] {
- def writes(t: Exception): JsValue = JsString(t.toString)
- def reads(json: JsValue): JsResult[Exception] = Json.fromJson[String](json) map {new Exception(_)}
- }
- implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
- // Output:
- http://localhost:9000/json/user/defined
- {"userId":55,"error":"java.lang.RuntimeException: qwerty"}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement