2017-08-15 18 views
0

我已經學會了Scala的,油滑的,阿卡2個月,我做阿卡的項目時出現問題...斯卡拉斯利克 - 省略ID列(AUTO_INCREMENT)

// This case class is to use for parsing data from request 
// case class UserTransaction(sender: String, recipient: String, amount: Int) 

//This one is to use for reflecting database 
case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int) 

class UserTransactionModelDB(tag: Tag) extends Table[UserTransactionDB](tag, "usertransaction") 
{ 
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc) 
    def sender = column[String]("sender") 
    def recipient = column[String]("recipient") 

    def amount = column[Int]("amount") 

    override def * = 

     (sender, recipient, amount, id) <> (UserTransactionDB.tupled, UserTransactionDB.unapply) 

} 

我想發送POST請求(JSON)以阿卡這樣的:

{"sender" : "S" , "recipient" : "R", "amount" : 100} 

現在,我想用僅僅只有一個案例類的UserTransaction(沒有UserTransactionDB「ID」字段),不僅反映了數據庫,並同時也解析從數據請求。這可能嗎 ?

謝謝你,對不起我的英文!

+0

什麼JSON庫您使用?我假設'spray-json' ...在這種情況下,您可以提供一個噴射json序列化器,它可以擺脫'id'字段。 – mfirry

+0

@mfirry是的,我正在使用jsonFormat4(UserTransactionDB.apply) – dOshu

+0

@mfirry你的意思是這個嗎? https://github.com/spray/spray-json#providing-jsonformats-for-other-types – dOshu

回答

0

嘗試用自定義格式...的東西沿着這些路線:

case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int) 

object MyJsonProtocol extends DefaultJsonProtocol { 
    implicit object UserTransactionJsonFormat extends RootJsonFormat[UserTransactionDB] { 
    def write(c: UserTransactionDB) = 
     JsArray(JsString(c.sender), JsString(c.recipient), JsNumber(c.amount)) 

    def read(value: JsValue) = value match { 
     case JsArray(Vector(JsString(sender), JsString(recipient), JsNumber(amount))) => 
     new UserTransactionDB(sender, recipient, amount.toInt) 
     case _ => deserializationError("UserTransactionDB expected") 
    } 
    } 
}