2

基本场景:

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 字段/案例类参数如何默认为值?

4

1 回答 1

4

我可能会尝试这样的事情:

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))
于 2013-07-08T21:48:51.903 回答