2017-08-15 51 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") 
    } 
    } 
}