将平面json对象映射到层级对象

时间:2014-04-07 01:37:50

标签: playframework-2.0

我正在使用Play 2.2.x

我想使用Format将平面json对象映射到分层对象结构。这是一个例子。

case class Hobby(id: String, name: String)
case class PersonWithHobby(id: String, name: String, hobby: Hobby)

但我的json是一个扁平的结构

{"id":"123, "name":"Joe", hobbyId:"abc", "hobbyName":"programming"}

我正在试图弄清楚如何做到这一点;

val personFormat = (
    (__ \ "id").format[String] and
    (__ \ "name").format[String] and
    ((__ \ "id").json.pick[String] and 
     (__ \ "name").json.pick[String]).format[Hobby]
)

当然,上面的代码不起作用。它只是想表明我想做什么。

1 个答案:

答案 0 :(得分:1)

这是定义格式的好方法(结合ScalaJsonCombinators中的一些概念):

val personFormat: Format[PersonWithHobby] = (
(__ \ "id").format[String] and
(__ \ "name").format[String] and
  (
    (__ \ "hobbyId").format[String] and
    (__ \ "hobbyName").format[String]
  )(Hobby.apply, unlift(Hobby.unapply))
)(PersonWithHobby.apply, unlift(PersonWithHobby.unapply))