您如何从嵌套在JSON数组中的JSON对象解码Date字段?
示例JSON:
[
{
"msys": {
"relay_message": {
"content": {
"headers": [
{
"Date": "Mon, 4 Jul 2016 15:53:14 +0100"
},
{
"Message-ID": "<484810298443-112311-xqxbby@mail.there.com>"
}
],
"html": "<p>Hi there <strong>SparkPostians</strong>.</p>",
"subject": "We come in peace",
"text": "Hi there SparkPostians.",
"to": [
"your@yourdomain.com"
]
},
"msg_from": "me@here.com",
}
}
}
]
访问日期时遇到麻烦,因为它嵌套在Headers数组中。有人有什么想法吗?
case class InboundEmail(recipients: Recipients, from: String, content: Content)
case class Recipients(to: List[String], cc: Option[List[String]])
case class Content(subject: String, body: String)
object InboundEmail {
implicit val decoder: Decoder[InboundEmail] = (c: HCursor) ⇒
for {
toList <- c.downArray.downField("msys").downField("relay_message").downField("content").downField("to").as[List[String]]
ccList <- c.downArray.downField("msys").downField("relay_message").downField("content").downField("cc").as[Option[List[String]]]
from <- c.downArray.downField("msys").downField("relay_message").downField("msg_from").as[String]
subject <- c.downArray.downField("msys").downField("relay_message").downField("content").downField("subject").as[String]
body <- c.downArray.downField("msys").downField("relay_message").downField("content").downField("html").as[String]
} yield {
new InboundEmail(Recipients(toList, ccList), from, Content(subject: String, body: String))
}
}
答案 0 :(得分:1)
您可以将以下内容添加到您的理解中,以将日期提取为Option [String]
date <- c.downArray.downField("msys").downField("relay_message").downField("content").downField("headers").as[List[Map[String, String]]].map(_.find(_.contains("Date")).flatMap(_.get("Date")))