List [(java.util.UUID, String, String, String, Int, Int, Int, Int, java.sql.Timestamp)] 유형에 대한 Json deserializer가 없습니다.

신화적인 프로그래머

내 스칼라 스킬은 부족하지만 이것으로 씨름하고 있습니다. 하지만 JSON 직렬화 및 역 직렬화하는 데 문제가 있습니다. 나는 StackOverflow를 검색하고 검색했지만 불행히도 함께 모을 수는 없습니다.

그래서 이것이 나의 최후의 수단입니다 ..

내 모델은 다음과 같습니다.

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)

  }

시간 내 주셔서 감사합니다!

신화적인 프로그래머

케이, 달콤 해.

내 모델을 수정했습니다.

case class User(
  id:UUID,
  username: String,
  password: String,
  email: String,
  comment_score_down: Option[Int],
  comment_score_up: Option[Int],
  post_score_down: Option[Int],
  post_score_up: Option[Int],
  created_on: Timestamp)

object Users extends Table[User]("users"){     

또한 사용자의 매개 변수 대신 User 유형을 반환 할 수 있도록 개체 서명을 변경했습니다. 그리고 프로젝션 방법 (*)에 <> (User, User.unapply _)를 추가하면됩니다.

하지만 내 컨트롤러에서 :

나는 단지 필요했다 :

  implicit object UserWrites extends Writes[User] {

    def writes(u: User) = Json.obj(
         "id" -> JsString(u.id.toString),
         "username" -> JsString(u.username),
         "password" -> JsString(u.password),
         "email" -> JsString(u.email),
         "comment_score_down" -> JsNumber(u.comment_score_down.getOrElse(0).toInt),
         "comment_score_up" -> JsNumber(u.comment_score_up.getOrElse(0).toInt),
         "post_score_down" -> JsNumber(u.post_score_down.getOrElse(0).toInt),
         "post_score_up" -> JsNumber(u.post_score_up.getOrElse(0).toInt),
         "created_on" -> JsString(u.created_on.toString)
    ) 


  }

컨트롤러 클래스의 멤버로.

이제 내 컨트롤러 작업은 다음과 같습니다.

  def getUsers = Action {

    val json = database withSession {
      val users = for (u <- Users) yield u
      Json.toJson(users.list)
    }
    Ok(json).as(JSON)
  }

편집하다:

또는 getUsers 코드를 findAll 메소드로 내 모델로 옮겼고 쓰기 가능 항목도 거기로 옮겼습니다. 컨트롤러에있는 데이터 로직이 마음에 들지 않았습니다.

따라서 내 컨트롤러에는 메서드 / 작업 만 있습니다.

  def getUsers = Action {
    Ok(Users.findAll).as(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: Option[Int],
  comment_score_up: Option[Int],
  post_score_down: Option[Int],
  post_score_up: Option[Int],
  created_on: Timestamp)

object Users extends Table[User]("users") {

  lazy val database = Database.forDataSource(DB.getDataSource())

  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[Option[Int]]("comment_score_down")
  def comment_score_up = column[Option[Int]]("comment_score_up")
  def post_score_down = column[Option[Int]]("post_score_down")
  def post_score_up = column[Option[Int]]("post_score_up")
  def created_on = column[Timestamp]("created_on")

  implicit object UserWrites extends Writes[User] {

    def writes(u: User) = Json.obj(
         "id" -> JsString(u.id.toString),
         "username" -> JsString(u.username),
         "password" -> JsString(u.password),
         "email" -> JsString(u.email),
         "comment_score_down" -> JsNumber(u.comment_score_down.getOrElse(0).toInt),
         "comment_score_up" -> JsNumber(u.comment_score_up.getOrElse(0).toInt),
         "post_score_down" -> JsNumber(u.post_score_down.getOrElse(0).toInt),
         "post_score_up" -> JsNumber(u.post_score_up.getOrElse(0).toInt),
         "created_on" -> JsString(u.created_on.toString)
    )
  }

  def * = id ~ username ~ password ~ email ~ comment_score_down ~
    comment_score_up ~ post_score_down ~ post_score_up ~ created_on <>
    (User, User.unapply _)

  def findByPK(pk: UUID) =
    for (entity <- Users if entity.id === pk) yield entity

  def findAll = database withSession {
      val users = for (u <- Users) yield u
      Json.toJson(users.list)
    }

}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관