Advertisement
mitrakov

Scala Play: json mapping (custom types)

Mar 5th, 2018
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.76 KB | None | 0 0
  1. // 1. Let's test custom types for Json serializer
  2. import play.api.libs.json._
  3.  
  4. case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
  5.  
  6. // add to routes: GET    /json/user/defined    controllers.TestController.jsonUserDefined
  7. def jsonUserDefined = Action {
  8.   val result = LastError(None, 55, Some(new RuntimeException("qwerty")))
  9.   Ok(Json.toJson(result))
  10. }
  11.  
  12.         // Compile output:
  13.         // Error:(69, 19) No Json serializer found for type TestController.this.LastError.
  14.         // Try to implement an implicit Writes or Format for this type.
  15.         //  Ok(Json.toJson(result))
  16.  
  17. // 1.1. Now we add implicit serializer
  18. case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
  19. implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
  20.  
  21.         // Compile output:
  22.         // Error:(65, 62) No instance of play.api.libs.json.Writes is available for scala.Option[java.lang.Exception]
  23.         // in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
  24.         // implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
  25.  
  26. // 1.3. so we need to provide extra implicit value to serialize Exception type
  27. case class LastError(id: Option[Long] = None, userId: Long, error: Option[Exception] = None)
  28. implicit val exceptionFormat: Format[Exception] = new Format[Exception] {
  29.   def writes(t: Exception): JsValue = JsString(t.toString)
  30.   def reads(json: JsValue): JsResult[Exception] = Json.fromJson[String](json) map {new Exception(_)}
  31. }
  32. implicit val lastErrToJson: Writes[LastError] = Json.writes[LastError]
  33.  
  34.         // Output:
  35.         http://localhost:9000/json/user/defined
  36.         {"userId":55,"error":"java.lang.RuntimeException: qwerty"}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement