Skip to content

Instantly share code, notes, and snippets.

@elyphas
Created June 14, 2020 21:04
Show Gist options
  • Save elyphas/6ee349ac79e531c2b7d98925374587dc to your computer and use it in GitHub Desktop.
Save elyphas/6ee349ac79e531c2b7d98925374587dc to your computer and use it in GitHub Desktop.
case class JsonObject(fields: HList ) extends JsonValue
implicit def hlistObjectEncoder[K <: Symbol, H, T <: HList]( implicit
witness: Witness.Aux[K],
hEncoder: Lazy[JsonEncoder[H]],
tEncoder: JsonObjectEncoder[T]
): JsonObjectEncoder[FieldType[K, H] :: T] = {
val fieldName: String = witness.value.name
createObjectEncoder { hlist =>
val head = hEncoder.value.encode(hlist.head)
val tail = tEncoder.encode(hlist.tail)
JsonObject( (fieldName ->> head) :: tail.fields )
}
}
////In the main method.
val iceCream = IceCream("Sundae", 1, 22.33, false)
val JsonObject(fields) = JsonEncoder[IceCream].encode(iceCream)
println ( fields )
println ( fields("numCherries") )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment