Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz
Created July 7, 2011 10:16
Show Gist options
  • Save gakuzzzz/1069242 to your computer and use it in GitHub Desktop.
Save gakuzzzz/1069242 to your computer and use it in GitHub Desktop.
Conceptパターンを再帰的にやってみた
scala> import Json._
import Json._
scala> toJson(List(10, 20, 30))
res0: String = [10, 20, 30]
scala> toJson(List("aaa", "bbb", "ccc"))
res1: String = ["aaa", "bbb", "ccc"]
scala> toJson(List(List(1, 2, 3), List(4, 5), List(6, 7, 8, 9)))
res2: String = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
scala> toJson(List(Map("aaa" -> List(1, 2), "bbb" -> List(3)), Map("ccc" -> List(4, 5, 6), "ddd" -> List())))
res3: String = [{"aaa": [1, 2], "bbb": [3]}, {"ccc": [4, 5, 6], "ddd": []}]
object Json {
trait ToJson[-A] {
def apply(value: A): String
}
def toJson[A](value: A)(implicit t: ToJson[A]): String = t(value)
implicit def traversableToJson[A](implicit t: ToJson[A]) = new ToJson[Traversable[A]] {
def apply(value: Traversable[A]): String = value.map(n => toJson(n)).mkString("[", ", ", "]")
}
implicit def mapToJson[A, B](implicit t: ToJson[B]) = new ToJson[Map[A, B]] {
def apply(value: Map[A, B]): String = value.map {
case (k, v) => toJson(k.toString) + ": " + toJson(v)
}.mkString("{", ", ", "}")
}
implicit val stringToJson = new ToJson[String] {
def apply(value: String): String = "\"" + value + "\""
}
implicit val intToJson = new ToJson[Int] {
def apply(value: Int): String = value.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment