Skip to content

Instantly share code, notes, and snippets.

@tuxdna
Last active December 31, 2015 03:19
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 tuxdna/7926531 to your computer and use it in GitHub Desktop.
Save tuxdna/7926531 to your computer and use it in GitHub Desktop.
Scala implementation of toJson
object tojson extends App {
def toJson(a: Any): String = {
a match {
// number
case m: Number => m.toString
// string
case m: String => "\"" + m + "\""
case m: Map[AnyRef, AnyRef] => {
"{" + (m map { x => val key = x._1; toJson(key) + ": " + toJson(m(key)) } mkString (", ")) + "}"
}
case l: Seq[AnyRef] => { "[" + (l map (toJson(_)) mkString (",")) + "]" }
// for anything else: tuple
case m: Product => toJson(m.productIterator.toList)
case m: AnyRef => "\"" + m.toString + "\""
}
}
class Person(val name: String, val country: String) {
override def toString = s"Person(Name: $name, Country: $country)"
}
val s = "Hello"
val i = 120
val l = List(1, 2, 3)
val m = Map("A" -> 230, "B" -> 2)
val ml = Map("A" -> l, "B" -> l)
val tuple = (i, l, m, ml, new Person("Bond", "Italy"))
println(toJson(s))
println(toJson(i))
println(toJson(l))
println(toJson(m))
println(toJson(ml))
println(toJson(tuple))
}
@tuxdna
Copy link
Author

tuxdna commented Dec 12, 2013

OUTPUT:

"Hello"
120
[1,2,3]
{"A": 230, "B": 2}
{"A": [1,2,3], "B": [1,2,3]}
[120,[1,2,3],{"A": 230, "B": 2},{"A": [1,2,3], "B": [1,2,3]},"Person(Name: Bond, Country: Italy)"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment