[英]toJson in PlayFramework2 for list of objects
I've read this answer about how simple it is.. 我已经读过这个答案,很简单。
But if if I have list of Objects but not just strings: 但是,如果我有对象列表而不只是字符串:
case class Article(
title:String,
description:String,
examples: List[Example]
)
There is Example case class: 有Example案例类:
case class Example(meaning:String, proofs:List[String])
Then how I could transform my Article to json string? 那我该如何将Article转换为json字符串呢?
If I use: 如果我使用:
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()
)
)
)
}
I got an error: No unapply function found
我收到一个错误:
No unapply function found
When I try to write my unapply method, I got different error about apply.. Don't want to spoil.. Do you have an answer or at least a suggestion? 当我尝试编写我的不应用方法时,我遇到了关于应用的不同错误。.不想破坏..您有答案还是至少有建议?
Along with your model, you can define an implicit typeclass Writes[T]
which is able to convert your model into a JsValue
: 与模型一起,您可以定义一个隐式类型类
Writes[T]
, JsValue
可以将模型转换为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
)
}
Then it is as simple as: Json.toJson(article)
然后就这么简单:
Json.toJson(article)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.