Skip to content

Instantly share code, notes, and snippets.

@jnd71
Created August 6, 2015 14:12
Show Gist options
  • Save jnd71/f88b5711b55f389a96ed to your computer and use it in GitHub Desktop.
Save jnd71/f88b5711b55f389a96ed to your computer and use it in GitHub Desktop.
Argonaut decoding alternating JSON type
//In this case, we are decoding a type `Teams` from a third party service
//If `Teams` has any elements, the presented JSON is an Array of `Team`
//If `Teams` is empty, is is suppoed to be Optional. However, sometimes when `Teams` is empty the service returns an empty JSON object
import argonaut._, Argonaut._
case class Team(id: Int, name: String)
object Team {
implicit val decodeTeamJson: DecodeJson[Team] = { DecodeJson(h => for {
id <- (h --\ "id").as[Int]
name <- (h --\ "name").as[String]
} yield new Team(id, name))
}
}
type Teams = List[Team]
case class Person(id: Int, name: String, teams: Option[Teams])
object Person {
implicit val decodeJson: DecodeJson[Conference] = { DecodeJson(h => for {
id <- (h --\ "id").as[Int]
name <- (h --\ "name").as[String]
teams <- (h --\ "teams").focus match {
case Some(j) => j.isArray match {
case true => j.as[Option[Teams]]
case false => DecodeResult.ok(None)
}
case None => DecodeResult.ok(None)
}
} yield new Conference(id, name, subdivisions, teams))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment