Skip to content

Instantly share code, notes, and snippets.

@bkase
Forked from kmizu/Jsson.scala
Last active December 10, 2015 01:48
Show Gist options
  • Save bkase/4361770 to your computer and use it in GitHub Desktop.
Save bkase/4361770 to your computer and use it in GitHub Desktop.
Type-safe concise JSON DSL
import org.json.{JSONObject, JSONArray}
/**
* Forked from https://gist.github.com/1240749
* Modified by bkase
*
* A concise typesafe JSON DSL in Scala.
* When you want to use, only
* import Jsson._ is needed.
* {
* import Jsson._
* val obj = %(
* ...
* )
* }
*/
object Jsson {
sealed abstract class JValue {
def toJSONValue: Any
}
sealed abstract class JElem extends JValue
case class JString(base: String) extends JElem {
def toJSONValue: String = base
}
case class JNumber(base: Long) extends JElem {
def toJSONValue: Long = base
}
case class JArray(base: List[JValue]) extends JValue with Traversable[JValue] {
def foreach[U](f: (JValue) => U) {
base.foreach(f)
}
def toJSONArray: JSONArray =
base.foldLeft(new JSONArray()){
case (building, next) => building.put(next.toJSONValue)
}
def toJSONValue: JSONArray = this.toJSONArray
}
case class JObject(base: Map[JString, JValue]) extends JValue with Traversable[(JString, JValue)] {
def foreach[U](f: ((JString, JValue)) => U) {
base.foreach(f)
}
def toJSONObject: JSONObject =
base.foldLeft(new JSONObject()){
case (building, (prop, value)) => building.put(prop.base, value.toJSONValue)
}
def toJSONValue: JSONObject = this.toJSONObject
}
implicit def stringToJString(input: String) = JString(input)
implicit def intToJNumber(input: Int) = JNumber(input)
implicit def longToJNumber(input: Long) = JNumber(input)
implicit def listToJArray(input: List[JValue]) = JArray(input)
implicit def mapToJObject(input: Map[JString, JValue]) = JObject(input)
def $(elements: JValue*): JArray = JArray(elements.toList)
def %(tuples: (String, JValue)*) = JObject(tuples.map(x => (JString(x._1), x._2)).toMap)
def main(args: Array[String]) {
// Example program
val obj = %(
"x" -> 10,
"y" -> 20,
"z" -> %(
"a" -> $(1, 2, 3, 4, 5),
"b" -> $(%("a" -> "b"), %())
)
)
println(obj.foreach(x => println(x + ", magic")))
val listList = $($(1,2), 2)
println(listList.toJSONArray)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment