I defined a user which has a "video" information:
case class User(name:String, video: Option[Video])
case class Video(title:String, url:String)
And we have such a json:
{
"name": "somename",
"video": {
"title": "my-video",
"url": "https://youtube.com/watch?v=123123"
}
}
I can use such code to parse it:
implicit def DecodeUser: DecodeJson[User] = for {
name <- as[String]("name")
video <- as[Option[Video]]("video")
} yield User(name, video)
implicit def DecodeVideo: DecodeJson[Option[Video]] = for {
titleOpt <- as[Option[String]]("title")
urlOpt <- as[Option[String]]("url")
} yield (titleOpt, urlOpt) match {
case (Some(title), Some(url)) => Video(title, url)
case _ => None
}
From the DecodeVideo
, you can see I just want to provide the video only if both "title" and "url" provided.
It's working well if the json contains "video" section. But if it doesn't, argonaut will report that "video" section is not provided.
How to make "video" optional?