Skip to content

Instantly share code, notes, and snippets.

@maheshkelkar
Created September 17, 2015 17:40
Show Gist options
  • Save maheshkelkar/1fe6d36d31d6b4c51a7f to your computer and use it in GitHub Desktop.
Save maheshkelkar/1fe6d36d31d6b4c51a7f to your computer and use it in GitHub Desktop.
circe json parsing question
case class SubServerConfig(
val a: String = "inside-test",
val b: Int = 9999
)
case class ServerConfig(
val a: String = "outside-test",
val b: Int = 8888,
val c: List[SubServerConfig] = List()
)
// define some boilerplate decoders, utilizing the two constructors via decoders
val dec1 = Decoder.instance[ServerConfig](c => for (s <- c.downField("a").as[String]; i <- c.downField("b").as[Int]; l <- c.downField("c").as[List[SubServerConfig]]) yield ServerConfig(s, i, l))
val dec2 = Decoder.instance[ServerConfig](c => for (s <- c.downField("a").as[String]) yield ServerConfig(s))
val dec3 = Decoder.instance[ServerConfig](c => for (i <- c.downField("b").as[Int]) yield ServerConfig("bad", i))
implicit val serverConfigDecoder = dec1 ||| dec2 ||| dec3
val dec11 = Decoder.instance[SubServerConfig](c => for (s <- c.downField("a").as[String]; i <- c.downField("b").as[Int]) yield SubServerConfig(s, i))
val dec12 = Decoder.instance[SubServerConfig](c => for (s <- c.downField("a").as[String]) yield SubServerConfig(s))
val dec13 = Decoder.instance[SubServerConfig](c => for (i <- c.downField("b").as[Int]) yield SubServerConfig("bad", i))
implicit val subServerConfigDecoder = dec11 ||| dec12 ||| dec13
val str1 = """{"a":"outer","b":5}"""
val out1 = decode[ServerConfig](str1)
println(out1)
//Right(ServerConfig(outer,8888,List()))
val str2 = """{"a":"outer"}"""
val out2 = decode[ServerConfig](str2)
println(out2)
//Right(ServerConfig(outer,8888,List()))
val str3 = """{"b":5}"""
val out3 = decode[ServerConfig](str3)
println(out3)
//Right(ServerConfig(bad,5,List()))
val str11 = """{"a":"outer","b":5,"c":[{"b":2221,"a":"inner1"}]}"""
val out11 = decode[ServerConfig](str11)
println(out11)
//Right(ServerConfig(outer,5,List(SubServerConfig(inner1,2221))))
val str12 = """{"a":"outer","b":5,"c":[{"a":"inner1"}]}"""
val out12 = decode[ServerConfig](str12)
println(out12)
//Right(ServerConfig(outer,8888,List()))
val str13 = """{"a":"outer","b":5,"c":[{"b":2221}]}"""
val out13 = decode[ServerConfig](str13)
println(out13)
//Right(ServerConfig(outer,8888,List()))
val str111 = """{"a":"outer","b":5,"c":[{"b":2221,"a":"inner1"},{"a":"inner2"}]}"""
val out111 = decode[ServerConfig](str111)
println(out111)
//Right(ServerConfig(outer,8888,List()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment