scala 使用 play.api.libs.json 将对象序列化为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11979638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
serializing objects to json with play.api.libs.json
提问by LuxuryMode
I'm trying to serialize some relatively simple models into json. For example, I'd like to get the json representation of:
我正在尝试将一些相对简单的模型序列化为 json。例如,我想获得以下 json 表示:
case class User(val id: Long, val firstName: String, val lastName: String, val email: Option[String]) {
def this() = this(0, "","", Some(""))
}
Do i need to write my own Format[User] with the appropriate reads and writes methods or is there some other way? I've looked at https://github.com/playframework/Play20/wiki/Scalajsonbut I'm still a bit lost.
我是否需要使用适当的读写方法编写自己的 Format[User] 或者还有其他方法吗?我看过https://github.com/playframework/Play20/wiki/Scalajson但我还是有点迷茫。
回答by Travis Brown
Yes, writing your own Formatinstance is the recommended approach. Given the following class, for example:
是的,推荐的方法是编写自己的Format实例。给定以下类,例如:
case class User(
id: Long,
firstName: String,
lastName: String,
email: Option[String]
) {
def this() = this(0, "","", Some(""))
}
The instance might look like this:
该实例可能如下所示:
import play.api.libs.json._
implicit object UserFormat extends Format[User] {
def reads(json: JsValue) = User(
(json \ "id").as[Long],
(json \ "firstName").as[String],
(json \ "lastName").as[String],
(json \ "email").as[Option[String]]
)
def writes(user: User) = JsObject(Seq(
"id" -> JsNumber(user.id),
"firstName" -> JsString(user.firstName),
"lastName" -> JsString(user.lastName),
"email" -> Json.toJson(user.email)
))
}
And you'd use it like this:
你会像这样使用它:
scala> User(1L, "Some", "Person", Some("[email protected]"))
res0: User = User(1,Some,Person,Some([email protected]))
scala> Json.toJson(res0)
res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"[email protected]"}
scala> res1.as[User]
res2: User = User(1,Some,Person,Some([email protected]))
See the documentationfor more information.
有关更多信息,请参阅文档。
回答by Pawe? Kozikowski
Thanks to the fact User is a case class you could also do something like this:
由于 User 是一个案例类,您还可以执行以下操作:
implicit val userImplicitWrites = Json.writes[User]
val jsUserValue = Json.toJson(userObject)
without writing your own Format[User]. You could do the same with reads:
无需编写自己的格式[用户]。你可以对读取做同样的事情:
implicit val userImplicitReads = Json.reads[User]
I haven't found it in the docs, here is the link to the api: http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json.Json$
我没有在文档中找到它,这里是 api 的链接:http: //www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json。 JSON$

