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