2013-03-19 46 views
1

我正在關注play-salat(github.com/leon/play-salat)爲json輸入創建模型並保存到mongodb。我怎樣才能創建隱藏json讀取List收集可能會在輸入json中丟失?如果輸入json中缺少'位置',以下代碼會給我提供驗證錯誤。創建隱式json讀取列表集合,可能從輸入json中缺少

case class LIProfile(
    id: ObjectId = new ObjectId, 
    positions: List[Position] = Nil 
) 

object LIProfile extends LIProfileDAO with LIProfileJson 

trait LIProfileDAO extends ModelCompanion[LIProfile, ObjectId] { 
    def collection = mongoCollection("liprofiles") 
    val dao = new SalatDAO[LIProfile, ObjectId](collection) {} 

    // Indexes 
    collection.ensureIndex(DBObject("emailAddress" -> 1), "li_profile_email", unique = true) 

    // Queries 
    def findOneByEmail(email: String): Option[LIProfile] = dao.findOne(MongoDBObject("emailAddress" -> email)) 
} 


trait LIProfileJson { 

    implicit val liprofileJsonWrite = new Writes[LIProfile] { 
    def writes(p: LIProfile): JsValue = { 
     Json.obj(
     "id" -> p.id, 
     "positions" -> p.positions 
    ) 
    } 
    } 
    implicit val liprofileJsonRead = (
    (__ \ 'id).read[ObjectId] ~ 
    (__ \ 'positions).read (
      (__ \ 'values).read[List[Position]] 
      ) 
)(LIProfile.apply _) 
} 

回答

2

使用readNullable以檢索Option和其映射到包含列表或空列表。

implicit val liprofileJsonRead = (
    (__ \ 'id).read[ObjectId] ~ 
    (__ \ 'positions).readNullable (
    (__ \ 'values).read[List[Position]] 
).map { 
    case Some(l) => l 
    case None => Nil 
    } 
)(LIProfile) 

甚至更​​短:

implicit val liprofileJsonRead = (
    (__ \ 'id).read[ObjectId] ~ 
    (__ \ 'positions).readNullable (
    (__ \ 'values).read[List[Position]] 
).map { l => l.getOrElse(Nil) } 
)(LIProfile) 

我不太知道什麼進口的,你真的需要在這裏,我的代碼編譯使用:

import play.api.libs.json._ 
import play.api.libs.json.Reads._ 
import play.api.libs.functional.syntax._