【问题标题】:Add a Json object to JSON Array using scala play使用 scala play 将 Json 对象添加到 JSON 数组
【发布时间】:2016-04-20 16:24:34
【问题描述】:

这是我当前的 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)。 但它没有用。

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: json scala playframework playframework-2.0


    【解决方案1】:

    使用Json.arr:

    def getParentJSON = {
      Json.obj(
        "name" -> "James",
        "child" -> Json.arr(getChildJSON)
      )
    }
    
    def getChildJSON = {
      Json.obj(
        "id" -> "1234",
        "name" -> "Ruth",
        "grandChild" -> Json.arr(getGrandChildJSON)
      )
    }
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多