-
-
Save dant3/7420683 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.DynamicVariable | |
/** | |
* A concise JSON DSL in Scala. | |
* When you want to use, only | |
* import Jsson._ is needed. | |
* Note that this program change the semantics of standard -> operator. | |
* I recommend that you use enclosing block with Jsson as followings: | |
* { | |
* import Jsson._ | |
* val obj = %{ | |
* ... | |
* } | |
* } | |
*/ | |
object Jsson { | |
private val values = new DynamicVariable[Map[String, Any]](null) | |
class Arrow(receiver: String) { | |
def ->(value: Any) { | |
values.value = values.value + ((receiver, value)) | |
} | |
} | |
implicit def pimpArrow(arg: String): Arrow = new Arrow(arg) | |
def %(body: => Any): Map[String, Any] = { | |
values.withValue(Map[String, Any]()) { | |
body | |
values.value | |
} | |
} | |
def $(elements: Any*): List[Any] = { | |
elements.toList | |
} | |
def main(args: Array[String]) { | |
// Example program | |
val obj = %{ | |
"x" -> 10 | |
"y" -> 20 | |
"z" -> %{ | |
"a" -> $(1, 2, 3, 4, 5) | |
"b" -> $(6, 7, %{ "xx" -> "yy" }) | |
} | |
} | |
println(obj) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment