Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. Let's try create "Reads" manually
- import java.util.Date
- import javax.inject.Inject
- import play.api.libs.functional.syntax._
- import play.api.libs.json._
- import play.api.mvc._
- class TestController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
- case class Student(name: String, year_of_enter: Int, birth_day: Date)
- implicit val studentReads: Reads[Student] = (
- (JsPath \ "name").read[String] and
- (JsPath \ "year_of_enter").read[Int] and
- (JsPath \ "birth_day").read[Date]
- ) (Student.apply _)
- // add to routes file: POST /testJson controllers.TestController.testJson
- def testJson: Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
- val student = request.body.asOpt[Student]
- Ok(s"Got student!: $student")
- }
- }
- // POST json data
- // {"name": "Bobby", "year_of_enter": 2007, "birth_day": "1989-12-07"}
- // Output:
- // Got student!: Some(Student(Bobby,2007,Thu Dec 07 00:00:00 GMT+03:00 1989))
- // 2. Now try auto mapping:
- implicit val studentReads: Reads[Student] = Json.reads[Student]
- // Output:
- // Got student!: Some(Student(Bobby,2007,Thu Dec 07 00:00:00 GMT+03:00 1989))
- // 3. Naming conventions: snake_case vs. camelCase
- case class Student(name: String, yearOfEnter: Int, birthDay: Date)
- // Output:
- // Got student!: None
- // 4. Let's fix it!
- implicit val jsonNamingConfig = JsonConfiguration(SnakeCase)
- implicit val studentReads: Reads[Student] = Json.reads[Student]
- // Output:
- // 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