Skip to content

Instantly share code, notes, and snippets.

@hamnis
Last active May 15, 2018 18:46
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 hamnis/4505aaa449beeca9b2afdffa7fef6fca to your computer and use it in GitHub Desktop.
Save hamnis/4505aaa449beeca9b2afdffa7fef6fca to your computer and use it in GitHub Desktop.
package example
import io.circe.{DecodingFailure, JsonNumber, Decoder => CD, Json => CJ}
import argonaut.{Json => AJ}
object ArgoCirc extends App {
case class Person(name: String, age: Int)
object Person {
import argonaut._, Argonaut._
implicit val personCodec: CodecJson[Person] = CodecJson(
person =>
("name" := person.name) ->:
("age" := person.age) ->:
jEmptyObject,
c =>
for {
name <- (c --\ "name").as[String]
age <- (c --\ "age").as[Int]
} yield Person(name, age)
)
}
implicit def a2cE[A](implicit ae: argonaut.EncodeJson[A]): io.circe.Encoder[A] = io.circe.Encoder { a =>
toCirceAST(ae.encode(a))
}
implicit def a2cD[A](implicit ae: argonaut.DecodeJson[A]): CD[A] = {
CD.instance { cursor =>
val decoded = ae.decodeJson(toArgonautAST(cursor.value))
decoded.fold(
(msg, history) => {
println(history)
Left(DecodingFailure(msg, Nil))
},
x => Right(x)
)
}
}
def toCirceAST(json: argonaut.Json): CJ = {
json.fold(
CJ.Null,
CJ.fromBoolean,
num => CJ.fromBigDecimal(num.toBigDecimal),
CJ.fromString,
arr => CJ.fromValues(arr.map(toCirceAST)),
obj => CJ.fromFields(obj.toList.map{case (f, j) => f -> toCirceAST(j)})
)
}
def toArgonautAST(json: CJ): AJ = {
json.fold(
AJ.jNull,
AJ.jBool,
num => AJ.jNumber(num.toBigDecimal.get),
AJ.jString,
arr => AJ.jArray(arr.map(toArgonautAST).toList),
obj => AJ.jObject(argonaut.JsonObject.fromTraversableOnce(obj.toList.map{case (f, j) => f -> toArgonautAST(j)}))
)
}
val erlend = Person("Erlend", 37)
show(erlend)
println(decode[Person](stringify(erlend)))
def show[A: io.circe.Encoder](showable: A): Unit = {
println(stringify(showable))
}
def stringify[A: io.circe.Encoder](showable: A): String = {
import io.circe.syntax._
showable.asJson.noSpaces
}
def decode[A: io.circe.Decoder](input: String): A = {
io.circe.parser.decode[A](input).getOrElse(throw new IllegalArgumentException("Nope"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment