我的scala技能缺乏,但我一直在摔跤有了這個。但是我有序列化和反序列化JSON的問題。我搜索並搜索了StackOverflow,但不幸的是我無法將它拼湊在一起。找不到類型爲List [(java.util.UUID,String,String,String,Int,Int,Int,Int,Int,java.sql.Timestamp)]的Json反序列化程序]
所以這是我的最後一招..
我的模式是:
package models
import java.util.UUID
import java.sql.Timestamp
import play.api.db._
import play.api.Play.current
import play.api.libs.json._
import slick.driver.PostgresDriver.simple._
import Database.threadLocalSession
case class User(
id:UUID,
username: String,
password: String,
email: String,
comment_score_down: Int,
comment_score_up: Int,
post_score_down: Int,
post_score_up: Int,
created_on: Timestamp)
object Users extends
Table[(UUID, String, String, String, Int, Int, Int, Int, Timestamp)]("users"){
implicit object UserFormat extends Format[User] {
implicit object UUIDFormatter extends Format[UUID] {
def reads(s: JsString): UUID = java.util.UUID.fromString(s.toString)
def writes(uuid: UUID) = JsString(uuid.toString)
}
implicit object TimestampFormatter extends Format[Timestamp] {
def reads(s: JsValue): Timestamp = new Timestamp(s.toString.toLong)
def writes(timestamp: Timestamp) = JsString(timestamp.toString)
}
def reads(json: JsValue): User = User(
(json \ "id").as[UUID],
(json \ "username").as[String],
(json \ "password").as[String],
(json \ "email").as[String],
(json \ "comment_score_down").as[Int],
(json \ "comment_score_up").as[Int],
(json \ "post_score_down").as[Int],
(json \ "post_score_up").as[Int],
(json \ "created_on").as[Timestamp]
)
def writes(u: User): JsValue = JsObject(List(
"id" -> JsString(u.id.toString),
"username" -> JsString(u.username),
"password" -> JsString(u.password),
"email" -> JsString(u.email),
"comment_score_down" -> JsString(u.comment_score_down.toString),
"comment_score_up" -> JsString(u.comment_score_up.toString),
"post_score_down" -> JsString(u.post_score_down.toString),
"post_score_up" -> JsString(u.post_score_up.toString),
"created_on" -> JsString(u.created_on.toString)
))
}
def id = column[UUID]("ID", O.PrimaryKey) // This is the primary key column
def username = column[String]("username")
def password = column[String]("password")
def email = column[String]("email")
def comment_score_down = column[Int]("comment_score_down")
def comment_score_up = column[Int]("comment_score_up")
def post_score_down = column[Int]("post_score_down")
def post_score_up = column[Int]("post_score_up")
def created_on = column[Timestamp]("created_on")
def * = id ~ username ~ password ~ email ~ comment_score_down ~
comment_score_up ~ post_score_down ~ post_score_up ~ created_on
}
我的控制器:
def getUsers = Action {
val json = database withSession {
val users = for (u <- Users) yield u.*
Json.toJson(users.list)
}
Ok(json).as(JSON)
}
謝謝您的時間!
如果有一個類型爲「T」的反序列化器,那麼play也會知道如何反序列化List [T]'。 –