基本情景:
case class Something(
date: Option[Date],
timestamp: Option[Date] = Some(new Date)
);
class Users private() extends MongoRecord[Users] with ObjectIdPk[Users] {
def meta = Users;
object things extends MongoCaseClassListField[Users, Something](this);
};
object Users extends Users with MongoMetaRecord[Users] {
};
def something(json: JValue) = {
val something = json.extract[Something];// does not have a timestamp field.
decompose(something); // again no timestamp field.
Users.where(_.email eqs email).findAndModify(_.things addToSet something).updateOne(true);
};
问题:当没有timestamp
字段的JSON作为请求发送时,数据库条目根本没有timestamp
字段。
如果使用timestamp: Date
而不是timestamp: Option[Date]
,则JSON提取会引发MappingException
。
问:缺少的JSON字段/案例类参数如何默认为值?
答案 0 :(得分:3)
我可能会尝试这样的事情:
case class Something(date: Option[Date], timestamp: Option[Date]){
def this(date:Option[Date]) = this(date, Some(new Date))
}
这将创建一个单独的一个参数构造函数,并将默认日期传递给双参数构造函数。通过REPL运行它,您可以看到时间戳似乎设置正确:
scala> parse(""" { "date":"2013-07-08T21:37:10Z" } """)
res11: net.liftweb.json.JValue = JObject(List(JField(date,JString(2013-07-08T21:37:10Z))))
scala> res11.extract[Something]
res16: Something = Something(Some(Mon Jul 08 17:37:10 EDT 2013),Some(Mon Jul 08 17:43:52 EDT 2013))
scala> parse(""" {
| "date":"2013-07-08T21:37:10Z",
| "timestamp":"2013-07-08T21:37:10Z"
| } """)
res14: net.liftweb.json.JValue = JObject(List(JField(date,JString(2013-07-08T21:37:10Z)), JField(timestamp,JString(2013-07-08T21:37:10Z))))
scala> res14.extract[Something]
res17: Something = Something(Some(Mon Jul 08 17:37:10 EDT 2013),Some(Mon Jul 08 17:37:10 EDT 2013))