我正在使用Play 2.1和MongoJack为Mongo数据库映射和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
答案 0 :(得分: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._