Scala: Using circe and newtype to decode JSON with a field with variable type

Here’s one way you can quickly decode a JSON using circe: import io.circe._ import io.circe.generic.semiauto.deriveDecoder import io.circe.literal._ case class Example(id: String, field1: String) object Example { implicit val circeDecoder: Decoder\[Example\] = deriveDecoder\[Example\] } val exampleJsonIdAsString: Json = json"""{ "id": "12345", "field1": "something" }""" val example = exampleJsonIdAsString.as\[Example\] println(example) This prints Right(Example(12345,something)). This all works well if the types of the JSON fields are predictable. But what if you’re consuming some API that you don’t control and the same field sometimes comes with different types?...

September 6, 2020

TIL: Circe JSON decoding for sealed trait hierarchies

import io.circe.generic.auto._ import io.circe.parser.decode sealed trait Thing1 case class SubThing1(a: Int) extends Thing1 decode[Thing1]("""{"SubThing1": {"a": 1}}""") // Returns Right(SubThing1(1)) decode[SubThing1]("""{"a": 1}""") // Returns Right(SubThing1(1))

August 11, 2020