2016-01-15 54 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