【问题标题】:toJson in PlayFramework2 for list of objectsPlay Framework 2 中的 toJson 用于对象列表
【发布时间】:2013-08-19 17:28:01
【问题描述】:

我已阅读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 方法时,我收到了关于 apply 的不同错误。不想剧透。你有答案或至少有建议吗?

【问题讨论】:

    标签: json scala playframework-2.1


    【解决方案1】:

    与您的模型一起,您可以定义一个隐式类型类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)

    【讨论】:

    • 是的,一旦我了解了隐式的工作原理,这很容易。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多