[英]How to convert case class to JSON in Play framework 2.3.x (Scala)?
Anyone can show me how to convert case class class instances to JSON in Play framework (particularly Play v2.3.x) with Scala? 任何人都可以告诉我如何使用Scala将案例类类实例转换为Play框架(特别是Play v2.3.x)中的JSON?
For example I have code like this: 例如,我有这样的代码:
case class Foo(name: String, address: String)
def index = Action {
request => {
val foo = Foo("John Derp", "Jem Street 21") // I want to convert this object to JSON
Ok(Json.toJson(foo)) // I got error at here
}
}
The error message: 错误消息:
Cannot write an instance of com.fasterxml.jackson.data bind.JsonNode to HTTP response.
无法将com.fasterxml.jackson.data bind.JsonNode的实例写入HTTP响应。 Try to define a Writeable[com.fasterxml.jackson.databind.JsonNode]
尝试定义一个可写的[com.fasterxml.jackson.databind.JsonNode]
UPDATE: I found out the above error is caused by wrong import of the Json
class, it should be: import play.api.libs.json.Json
. 更新:我发现上面的错误是由于错误导入
Json
类引起的,它应该是: import play.api.libs.json.Json
。 However I still got error on implicit problem below. 但是我仍然在下面的隐含问题上有错误。
I have read this tutorial , but when I tried the implicit Writes[Foo]
code: 我已经阅读了本教程 ,但是当我尝试隐式的
Writes[Foo]
代码时:
implicit val fooWrites: Writes[Foo] = (
(JsPath \ "name").write[String] and
(JsPath \ "address").write[String]
)(unlift(Foo.unapply))
I got Can't resolve symbol and
and Can't resolve symbol unlift
error in Intellij. 我得到
Can't resolve symbol and
Can't resolve symbol unlift
中的Can't resolve symbol unlift
错误。 Also the tutorial's code looks complex just for the conversion of an object to JSON. 此外,教程的代码看起来很复杂,只是为了将对象转换为JSON。 I wonder if there is more simple way to do this?
我想知道是否有更简单的方法来做到这一点?
You can get an Writes[Foo]
instance by using Json.writes
: 您可以使用
Json.writes
获取Writes[Foo]
实例:
implicit val fooWrites = Json.writes[Foo]
Having this implicit in scope is all you need to convert Foo
to JSON. 将此隐含在范围内是将
Foo
转换为JSON所需的全部内容。 See the documetnation here and here for more info about JSON reads/writes. 有关JSON读/写的更多信息,请参阅此处和此处的文档。
The second problem - Can't resolve symbol and
- is an Intellij bug introduced in version 1.3 of the Scala plugin. 第二个问题 -
Can't resolve symbol and
- 是Scala插件1.3版中引入的Intellij错误 。 In version 1.3.3 of the Scala plugin, there's now a workaround - set preference checkbox: 在Scala插件的1.3.3版本中,现在有一个解决方法 - 设置首选项复选框:
Languages & Frameworks > Scala > Core (default) tab > Use old implicit search algorithm
语言和框架> Scala> Core(默认)选项卡>使用旧的隐式搜索算法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.