2016-01-15 31 views
3

这是我目前的JSON:JSON对象添加到JSON阵列使用Scala的发挥

{"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)。 但它没有奏效。

任何帮助将不胜感激。

感谢

回答

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

感谢那些工作! @danielnixon –

+1

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