Advertisement
mitrakov

Scala Play: json mapping

Jan 16th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.62 KB | None | 0 0
  1. // 1. Let's try create "Reads" manually
  2. import java.util.Date
  3. import javax.inject.Inject
  4.  
  5. import play.api.libs.functional.syntax._
  6. import play.api.libs.json._
  7. import play.api.mvc._
  8.  
  9. class TestController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  10.  
  11.   case class Student(name: String, year_of_enter: Int, birth_day: Date)
  12.  
  13.   implicit val studentReads: Reads[Student] = (
  14.     (JsPath \ "name").read[String] and
  15.       (JsPath \ "year_of_enter").read[Int] and
  16.       (JsPath \ "birth_day").read[Date]
  17.     ) (Student.apply _)
  18.  
  19.   // add to routes file: POST    /testJson    controllers.TestController.testJson
  20.   def testJson: Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  21.     val student = request.body.asOpt[Student]
  22.     Ok(s"Got student!: $student")
  23.   }
  24. }
  25.  
  26. // POST json data
  27. // {"name": "Bobby", "year_of_enter": 2007, "birth_day": "1989-12-07"}
  28.  
  29.         // Output:
  30.         // Got student!: Some(Student(Bobby,2007,Thu Dec 07 00:00:00 GMT+03:00 1989))
  31.  
  32. // 2. Now try auto mapping:
  33. implicit val studentReads: Reads[Student] = Json.reads[Student]
  34.  
  35.         // Output:
  36.         // Got student!: Some(Student(Bobby,2007,Thu Dec 07 00:00:00 GMT+03:00 1989))
  37.  
  38. // 3. Naming conventions: snake_case vs. camelCase
  39. case class Student(name: String, yearOfEnter: Int, birthDay: Date)
  40.  
  41.         // Output:
  42.         // Got student!: None
  43.  
  44. // 4. Let's fix it!
  45. implicit val jsonNamingConfig = JsonConfiguration(SnakeCase)
  46. implicit val studentReads: Reads[Student] = Json.reads[Student]
  47.  
  48.         // Output:
  49.         // Got student!: Some(Student(Bobby,2007,Thu Dec 07 00:00:00 GMT+03:00 1989))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement