Skip to content

Instantly share code, notes, and snippets.

@hohonuuli
Created January 17, 2021 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hohonuuli/9cd4ffdf91554c242ae4443baf39e88e to your computer and use it in GitHub Desktop.
Save hohonuuli/9cd4ffdf91554c242ae4443baf39e88e to your computer and use it in GitHub Desktop.
Example for medium article on Circe
#!/usr/bin/env amm
import $ivy.`io.circe::circe-core:0.13.0`
import $ivy.`io.circe::circe-generic:0.13.0`
import $ivy.`io.circe::circe-parser:0.13.0`
import io.circe._
import io.circe.generic.semiauto._
import io.circe.parser._
import io.circe.syntax._
import java.net.URL
import java.nio.file.{Files, Paths}
import java.util.{Base64, UUID}
import scala.util.Try
case class Blob(uuid: UUID, url: String, checksum: Array[Byte])
case class Catalog(uuid: UUID, name: Option[String], blobs: List[Blob])
implicit val byteArrayEncoder: Encoder[Array[Byte]] = new Encoder[Array[Byte]] {
final def apply(xs: Array[Byte]): Json =
Json.fromString(new String(Base64.getEncoder().encode(xs)))
}
implicit val byteArrayDecoder: Decoder[Array[Byte]] = Decoder
.decodeString
.emapTry(str => Try(Base64.getDecoder.decode(str.getBytes)))
implicit val blogDecoder: Decoder[Blob] = deriveDecoder
implicit val blogEncoder: Encoder[Blob] = deriveEncoder
implicit val catalogDecoder: Decoder[Catalog] = deriveDecoder
implicit val catalogEncoder: Encoder[Catalog] = deriveEncoder
val json = Files.readString(Paths.get("CirceDemo.json"))
val r = for {
doc <- parse(json)
e <- doc.as[List[Catalog]]
} yield e
r match {
case Left(e) =>
println(e)
case Right(v) =>
println(v.asJson)
}
// decode[List[Catalog]](json) match {
// case Left(e) =>
// println(e)
// case Right(v) =>
// println(v.asJson)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment