1

我读过这个答案是多么简单..

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

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 方法时,我得到了关于 apply 的不同错误..不想破坏..您有答案或至少有建议吗?

4

1 回答 1

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)

于 2013-08-19T09:28:01.430 回答