Semi-automatic Circe decoder for JsonString of slick-pg

If you need a decoder for storing JSON to a database or implicit conversion of a com.github.tminglei.slickpg.JsonString, you can us the semi-automatic derivation of Circe.

The following imports are neccessary.

import com.github.tminglei.slickpg.JsonString
import io.circe.Decoder
import io.circe.generic.semiauto._

Let`s assume, we have the following case class:

final case class MyClass(
    myId: Long,
    desc: String,
    structure: JsonString
)

The following implicit decoder is semi-automatically derived by Circe.

/**
 * Implicit Decoder for decoding the JsonString value
 */
implicit val decodeMyClassStructureJsonString: Decoder[JsonString] = deriveDecoder[JsonString]

Decoder and Encoder

An implicit decoder and encoder for the case class could be as follows.

// Circe codec for decoding a MyClass from JSON.
  implicit val decodeMyClass: Decoder[MyClass] = (c: HCursor) =>
    for {
      myId      <- c.downField("myId").as[Long]
      desc      <- c.downField("desc").as[String]
      structure <- c.downField("structure").as[JsonString]
    } yield
      MyClass(
        myId,
        orgadescisationUuid,
        structure
    )

  // Circe codec for encoding a MyClass to JSON.
  implicit val encodeMyClass: Encoder[MyClass] = (a: MyClass) =>
    Json.obj(
      ("myId", a.myId.asJson),
      ("desc", a.desc.asJson),
      ("structure", a.structure.value.asJson)
  )

Current versions:

  • slick-pg 0.15.2
  • circe 0.8.0