PlayFramework2中的toJson用于对象列表

时间:2013-08-18 21:22:39

标签: json scala playframework-2.1

我已经阅读this回答有多简单了......

但是,如果我有对象列表但不仅仅是字符串:

case class Article(
     title:String,
     description:String,
     examples: List[Example]
)

有案例类:

case class Example(meaning:String, proofs:List[String])

然后我如何将我的文章转换为json字符串?

如果我使用:

  def article(word:String) = Action {

    implicit val articleFormat = Json.format[Article]
    implicit val exampleFormat = Json.format[Example]

    val article = Article.article(word)

    Ok( Json.format(article) )

    // or: ?

    Ok( Json.obj("examples" -> article.examples) ) // this works but only for Examples alone.. without Article

    // or: ? 
     Ok( Json.obj("article" -> article) )

   // or:?

    Ok(
     Json.toJson( // works, but it is still not that I'm expecting (duplication of "examples"...like: "examples":"{\"examples\":[{\"meaning\":\"meaning1\",...)
       Map(
         "title" -> article.title,
         "description" -> article.description,
         "examples" -> Json.obj("examples" -> article.examples).toString()
       )
     )
   )

  }

我收到了错误:No unapply function found

当我尝试编写我的unapply方法时,我得到了关于申请的不同错误..不想破坏..你有答案或者至少有建议吗?

1 个答案:

答案 0 :(得分:5)

与模型一起,您可以定义一个隐式类型类Writes[T],它可以将您的模型转换为JsValue

implicit object ExampleWrites extends Writes[Example] {
  def writes(e: Example) = Json.obj(
    "meaning" -> e.meaning,
    "proofs" -> e.proofs
  )
}
implicit object ArticleWrites extends Writes[Article] {
  def writes(a: Article) = Json.obj(
    "title" -> a.title,
    "description" -> a.description,
    "examples" -> a.examples
  )
}

然后它就像:Json.toJson(article)

一样简单