在scala的play json中指定嵌套对象

时间:2016-04-19 16:26:29

标签: json scala playframework-2.0

鉴于此代码:

    case class SocialUser(firstName: String, lastName: String)
    case class UserDetails(avatarUrl: String, phone: String)

    // I want to avoid having to specify each SocialUser field one by one but just use the implicit write as stated below
    implicit val socialUserWrites = Json.writes[SocialUser] 
    implicit val userDetailsWrites = Json.writes[UserDetails]

现在,我怎么能以这种格式输出json?

{"user": {
      "firstName: "",
      "lastName": "",
      "details": {
        "avatarUrl": "",
        "phone": "",
      }
    }}

1 个答案:

答案 0 :(得分:2)

你错过了“UserDetail”中的“user”写道:

implicit val combinedUserWrites: Writes[CombinedUser] = (
  (__ \ "user").write[SocialUser] and
    (__ \ "user" \ "userDetails").write[UserDetails]
  )(unlift(CombinedUser.unapply))

x: CombinedUser = CombinedUser(SocialUser(f,l),UserDetails(a,p))

scala> res4: play.api.libs.json.JsValue = {"user":{"firstName":"f","lastName":"l","userDetails":{"avatarUrl":"a","phone":"p"}}}