1

我看不到这个问题的答案 - 有没有简单的方法可以做到这一点?我想获取一些对象 x 的列表并将其变成一个没有任何 hacky 代码的 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"
    }
  ]
}
4

2 回答 2

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)
}
于 2013-02-18T11:23:21.507 回答
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)
}
于 2013-02-18T18:15:43.430 回答