我无法看到答案 - 是否有一种简单的方法可以做到这一点?我想获取一些对象x的列表并将其转换为单个json对象而不需要任何hacky代码?我正在做一些丑陋的东西但是想把这个列表放到一个叫做'data'的对象中。我可以以某种方式将其映射到对象“数据”吗?
private def renderArticleJson(articles: Iterable[GraphedArticle]): String = {
val listToConvert = for (article <- articles) yield {
JsObject(
"articleId" -> Json.toJson(article.getArticleId)
:: "articleUrl" -> Json.toJson(article.getArticleUrl)
:: "graphId" -> Json.toJson(article.asVertex().getId.toString)
:: "fullName" -> Json.toJson(article.getTitle)
:: "imageUrl" -> Json.toJson(article.getImageUrl)
:: Nil
)
}
}
根据要求编辑:添加我想要的内容(现在通过第一个答案的帮助解决)
{
"data": [
{
"articleId": null,
"articleUrl": null,
"graphId": "#8:24",
"fullName": "hey",
"imageUrl": "hey"
},
{
"articleId": null,
"articleUrl": null,
"graphId": "#8:25",
"fullName": "hey",
"imageUrl": "hey"
},
{
"articleId": "b23c162d-b0af-4ce3-aebf-f33943492f95",
"articleUrl": null,
"graphId": "#8:26",
"fullName": "hey",
"imageUrl": "hey"
},
{
"articleId": "8afe310c-8337-4a8a-8406-5670249ba0a7",
"articleUrl": "hey",
"graphId": "#8:27",
"fullName": "hey",
"imageUrl": "hey"
}
]
}
答案 0 :(得分:2)
这是你的意思吗?
private def renderArticleJson(articles: Iterable[GraphedArticle]): String = {
val listToConvert = for (article <- articles) yield {
JsObject(
"articleId" -> Json.toJson(article.getArticleId)
:: "articleUrl" -> Json.toJson(article.getArticleUrl)
:: "graphId" -> Json.toJson(article.asVertex().getId.toString)
:: "fullName" -> Json.toJson(article.getTitle)
:: "imageUrl" -> Json.toJson(article.getImageUrl)
:: Nil)
}
val jsonList = Json.toJson(listToConvert)
Json.stringify(jsonList)
}
答案 1 :(得分:0)
感谢EEColor,我确实得到了我想要的东西。我给了他答案,但我使用的最终代码如下:
private def renderArticleJson(articles: Iterable[GraphedArticle]): String = {
val listToConvert = for (article <- articles) yield {
JsObject(
"articleId" -> Json.toJson(article.getArticleId)
:: "articleUrl" -> Json.toJson(article.getArticleUrl)
:: "graphId" -> Json.toJson(article.asVertex().getId.toString)
:: "fullName" -> Json.toJson(article.getTitle)
:: "imageUrl" -> Json.toJson(article.getImageUrl)
:: Nil)
}
val jsonList = Json.toJson(listToConvert.toSeq)
val result = JsObject("data" -> jsonList :: Nil)
Json.stringify(result)
}