Using Play's JSON autoformatting when json property names don't match

时间:2016-07-11 22:01:11

标签: json scala playframework

My JSON result have the naming convention like:

"account_id"
"location_type"

But my case classes have:

case class Employee(accountId: Int, locationType: String)

Is there a way to override the case classes property when JSON is being parsed?

Automapping: https://www.playframework.com/documentation/2.5.x/ScalaJsonAutomated

1 个答案:

答案 0 :(得分:2)

There are two things you can do here:

  1. Rename fields in your case class:

    case class Employee(account_id: Int, location_type: String)
    
  2. Write your custom Format:

    import play.api.libs.functional.syntax._
    import play.api.libs.json._
    
    implicit val employeeFormat: Format[Employee] = (
      (__ \ "account_id").format[Int] and
      (__ \ "location_type").format[String]
    )(Employee.apply, unlift(Employee.unapply))