Encoding and Decoding

circe uses Encoder and Decoder type classes for encoding and decoding. An Encoder[A] instance provides a function that will convert any A to a Json, and a Decoder[A] takes a Json value to either an exception or an A. circe provides implicit instances of these type classes for many types from the Scala standard library, including Int, String, and others. It also provides instances for List[A], Option[A], and other generic types, but only if A has an Encoder instance.

Encoding data to Json can be done using the .asJson syntax:

import io.circe.syntax._

val intsJson = List(1, 2, 3).asJson
// intsJson: io.circe.Json = JArray(
//   value = Vector(
//     JNumber(value = JsonLong(value = 1L)),
//     JNumber(value = JsonLong(value = 2L)),
//     JNumber(value = JsonLong(value = 3L))
//   )
// )

Use the .as syntax for decoding data from Json:

intsJson.as[List[Int]]
// res0: io.circe.Decoder.Result[List[Int]] = Right(value = List(1, 2, 3))

The decode function from the included parser module can be used to directly decode a JSON String:

import io.circe.parser.decode

decode[List[Int]]("[1, 2, 3]")
// res1: Either[io.circe.Error, List[Int]] = Right(value = List(1, 2, 3))