基本情况:
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。
Q:缺少的JSON字段/case类如何默认为一个值?
发布于 2013-07-08 21:48:51
我可能会尝试这样的方法:
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))https://stackoverflow.com/questions/17535212
复制相似问题