使用Scala Play将Json对象添加到JSON数组

3

这是我的当前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个回答

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)
  )
}

1
https://www.playframework.com/documentation/2.4.x/ScalaJson#Using-class-construction - danielnixon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接