2013-02-17 68 views
1

我看不到答案 - 有沒有簡單的方法來做到這一點?我想獲取一些對象x的列表,並將其轉換爲單個json對象,而不需要任何hacky代碼?我正在做一些醜陋的東西,但希望將這個列表放入一個名爲'data'的對象中。我可以以某種方式將其映射到對象「數據」?Play2和Scala(Jerkson) - JsObject的列表 - 如何轉換爲Json對象

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

你可以添加你想看到的結果字符串嗎? – EECOLOR 2013-02-17 23:51:47

+0

編輯 - 謝謝 – JasonG 2013-02-18 18:13:34

回答

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

謝謝這是非常有益的。 這是我最後用 – JasonG 2013-02-18 18:14:06

+0

(我把它發佈在答案中)的方法,但我給了你答案。 – JasonG 2013-02-18 18:16:18

+0

只需要注意一下,listToConvert必須是seq,因此您必須.toSeq它。 – JasonG 2013-02-18 18:16:39

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

在最後加上Nil是否是一個好習慣? – Apurv 2013-12-27 11:26:23