2015-09-03 24 views
1

我想轉義用於創建案例類的動態列表中的字符。在動態列表中轉義字符

case class Profile(biography: String, 
        userid: String, 
        creationdate: String) extends Serializable 

object Profile { 

    val cs = this.getClass.getConstructors 
    def createFromList(params: List[Any]) = params match { 
    case List(biography: Any, 
       userid: Any, 
       creationdate: Any) => Profile(StringEscapeUtils.escapeJava(biography.asInstanceOf[String]), 
              StringEscapeUtils.escapeJava(creationdate.asInstanceOf[String]), 
              StringEscapeUtils.escapeJava(userid.asInstanceOf[String])) 
    } 
} 

JSON.parseFull("""{"biography":"An avid learner","userid":"165774c2-a0e7-4a24-8f79-0f52bf3e2cda", "creationdate":"2015-07-13T07:48:47.924Z"}""") 
    .map(_.get.asInstanceOf[scala.collection.immutable.Map[String, Any]]) 
    .map { 
    m => Profile.createFromList(m.values.to[collection.immutable.List]) 
    } saveToCassandra("testks", "profiles", SomeColumns("biography", "userid", "creationdate")) 

我得到這個錯誤:

scala.MatchError: List(An avid learner, 165774c2-a0e7-4a24-8f79-0f52bf3e2cda, 2015-07-13T07:48:47.925Z) (of class scala.collection.immutable.$colon$colon) 

任何想法嗎?

+0

嘗試'.toList'而不是'.to [collection.immutable.List]' – Shadowlands

+0

感謝但同樣的錯誤。 – drecute

回答

1

使用與scala.util.parsing.json(自Scala 2.11以來已棄用的)不同的(外部)JSON庫可能會更簡單。

有一個lot of good Scala Json libraries,下面的例子使用json4s

import org.json4s._ 
import org.json4s.native.JsonMethods._ 

case class Profile(biography: String, userid: String, creationdate: String) 

val json = """{ 
| "biography":"An avid learner", 
| "userid":"165774c2-a0e7-4a24-8f79-0f52bf3e2cda", 
| "creationdate":"2015-07-13T07:48:47.924Z" 
|}""".stripMargin 

parse(json).extract[Profile] 
// Profile(An avid learner,165774c2-a0e7-4a24-8f79-0f52bf3e2cda,2015-07-13T07:48:47.924Z) 
+0

非常感謝。 – drecute