Created
May 4, 2018 06:09
-
-
Save fogfish/262df0e1bfee1770855025dd74f110f5 to your computer and use it in GitHub Desktop.
Scala shapeless HList to Json with io.circe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.circe.{Encoder, JsonObject, ObjectEncoder} | |
import shapeless.{::, HList, HNil} | |
import scala.reflect.ClassTag | |
/** | |
* val product = A(...) :: B(...) :: C(...) :: HNil | |
* product.asJson | |
* | |
* {"a": {...}, "b": {...}, "c": {...}} | |
*/ | |
object CodecHList { | |
implicit val encodeHNil: ObjectEncoder[HNil] = ObjectEncoder.instance(_ => JsonObject.empty) | |
implicit def encodeHCons[H: ClassTag, T <: HList](implicit | |
encodeH: Encoder[H], | |
encodeT: ObjectEncoder[T], | |
tag: ClassTag[H] | |
): ObjectEncoder[H :: T] = ObjectEncoder.instance { | |
case h :: t => (tag.runtimeClass.getSimpleName.toLowerCase -> encodeH(h)) +: encodeT.encodeObject(t) | |
} | |
} | |
// | |
// | |
import io.circe.syntax._ | |
import io.circe.generic.auto._ | |
case class A(a: String) | |
case class B(b: Int) | |
case class C(c: Double) | |
val gen = A("test") :: B(1) :: C(1.0) :: HNil | |
val json = gen.asJson | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment