使用scala play将Json对象添加到JSON Array

时间:2016-01-15 05:29:07

标签: json scala playframework playframework-2.0

这是我现在的json:

{"name":"James",
    "child": {"id":1234,"name":"Ruth",
        "grandchild":{"id":1111,"name":"Peter"}
    }
}

我想这样做:

{"name":"James",
    "child": [{"id":1234,"name":"Ruth",
        "grandChild":[{"id":1111,"name":"Peter"}]
     }]
}

以下是代码:

def getParentJSON = {
    Json.obj(
        "name"->"James",
        "child"->getChildJson
    )
}

def getChildJSON = {
    Json.obj(
        "id"->"1234",
        "name"->"Ruth",
        "grandChild"->getGrandChildJson
    )       
}

def getGrandChildJSON = {
    Json.obj(
        "id"->"1111",
        "name"->"Peter"
    )       
}

我尝试使用JsArray.append(getParentJSON)。 但它没有奏效。

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

使用Json.arr

def getParentJSON = {
  Json.obj(
    "name" -> "James",
    "child" -> Json.arr(getChildJSON)
  )
}

def getChildJSON = {
  Json.obj(
    "id" -> "1234",
    "name" -> "Ruth",
    "grandChild" -> Json.arr(getGrandChildJSON)
  )
}