Skip to content

Instantly share code, notes, and snippets.

@rlmark
Created February 24, 2018 00:01
Show Gist options
  • Save rlmark/0f089e8dca7c7dadcff188a66a9b120a to your computer and use it in GitHub Desktop.
Save rlmark/0f089e8dca7c7dadcff188a66a9b120a to your computer and use it in GitHub Desktop.
// JSON AST
sealed trait JSON
case object JSNull extends JSON
case class JSString(get: String) extends JSON
case class JSNumber(get: Int) extends JSON
case class JSObject(get: Map[String, JSON]) extends JSON
final case class Person(name: String, email: String)
// Given any value, write it to JSON AST
// JSONWriter is the typeclass
trait JsonWriter[A]{
def write(value: A): JSON
}
// These are instances of our typeclasse
object JsonWriterInstances{
implicit val stringWriter: JsonWriter[String] = {
new JsonWriter[String] {
def write(a: String) = JSString(a)
}
}
implicit val numberWriter: JsonWriter[Int] = {
new JsonWriter[Int]{
def write(a: Int) = JSNumber(a)
}
}
implicit val personWriter: JsonWriter[Person] = {
new JsonWriter[Person] {
def write(a: Person) = JSObject(Map(
"name" -> JSString(a.name),
"email" -> JSString(a.email)
))
}
}
}
object JSON { // You want this toJson method to take your implicit JsonWriter because then you don't need separate toJson methods for each type.
def toJson[A](a: A)(implicit jsonWriter: JsonWriter[A]): JSON = jsonWriter.write(a)
}
object Main {
import JsonWriterInstances._
def main(args: Array[String]): Unit = {
println(JSON.toJson("HI"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment