0

我正在使用 Play 2.1 和 MongoJack 为 Mongo db 映射以及 Json 序列化创建一个 scala 类。我想在这个模型中有一个选项元组(参见下面的“上传”)。但是,我无法让 Json Writes 为选项元组工作。

class Event (
  @BeanProperty @JsonProperty("name") val name: String,
  @BeanProperty @JsonProperty("message") val message: String
  ) {
  @ObjectId @Id @BeanProperty var eventId: String = _
  @BeanProperty @JsonProperty("upload") var upload: Option[(String, String, Int)] =  _
}

object Event {
  def apply(name: String,
         message: String): Event = new Event(name,message)

  def unapply(e: Event) = 
    new Some((e.name,
              e.message,
              e.upload) )

  import play.api.libs.json.Writes._
  val eventWrites: Writes[Event] = (
    (__ \ 'name).write[String] and
    (__ \ 'message).write[String] and
    (__ \ 'upload).write(Option[( // HOW TO WRITE A OPTIONAL TUPLE?
      (__ \ 'url).write[String] and
      (__ \ 'name).write[String] and
      (__ \ 'size).write[Int]
      tupled
    )])
    )(unlift(Event.unapply))
}

编辑1:

将上传初始值替换为

@BeanProperty @JsonProperty("upload") var upload: Option[(String, String, Int)] =  None
4

1 回答 1

2

你的写作看起来像这样:

val eventWrites: Writes[Event] = (
  (__ \ 'name).write[String] and
  (__ \ 'message).write[String] and
  (__ \ 'upload).writeNullable((
    (__ \ 'url).write[String] and
    (__ \ 'name).write[String] and
    (__ \ 'size).write[Int]).tupled))(unlift(Event.unapply))

你不需要导入Writes._

于 2013-08-03T07:36:33.623 回答