-
-
Save rrmckinley/6355794 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 org.json4s._ | |
import org.json4s.native.JsonMethods._ | |
import shapeless._ | |
import poly._ | |
import ops.hlist._ | |
import syntax.singleton._ | |
import record._ | |
object Record { | |
def keyAsString[F, V](f: FieldType[F, V])(implicit wk: shapeless.Witness.Aux[F]) = | |
wk.value.toString | |
} | |
object JSON { | |
def compact[A](a: A)(implicit st: toJSON.Case[A] { type Result <: JValue }): String = | |
org.json4s.native.JsonMethods.compact(render(st(a))) | |
def pretty[A](a: A)(implicit st: toJSON.Case[A] { type Result <: JValue }): String = | |
org.json4s.native.JsonMethods.pretty(render(st(a))) | |
} | |
object toJSON extends Poly1 { // Pullback1[JValue] { | |
implicit def nullToJSON = at[Null](_ => JNull) | |
implicit def doubleToJSON = at[Double](JDouble(_)) | |
implicit def bigIntToJSON = at[BigInt](JInt(_)) | |
implicit def bigDecimalToJSON = at[BigDecimal](JDecimal(_)) | |
implicit def numToJSON[V <% Long] = at[V](i => JInt(BigInt(i))) | |
implicit def stringToJSON = at[String](s => if (s == null) JNull else JString(s)) | |
implicit def boolToJSON = at[Boolean](JBool(_)) | |
implicit def jsonToJSON[V <: JValue] = at[V](identity) | |
implicit def dateToJSON[V <: java.util.Date](implicit f: Formats) = | |
at[V](s => if (s == null) JNull else JString(f.dateFormat.format(s))) | |
implicit def traversableToJSON[V, C[V] <: Traversable[V]](implicit st: Case.Aux[V, JValue]) = | |
at[C[V]](l => JArray(l.toList.map(v => toJSON(v)))) | |
implicit def recordToJSON[R <: HList, F, V](r: R) | |
(implicit folderttl2: MapFolder[R, List[JField], fieldToJSON.type]) = | |
JObject(r.foldMap(Nil: List[JField])(fieldToJSON)(_ ::: _)) | |
} | |
object fieldToJSON extends Poly1 { | |
implicit def f[F, V](implicit tjf: toJSON.Case[V] { type Result <: JValue }, wk: shapeless.Witness.Aux[F]) = at[FieldType[F, V]] { | |
f => (Record.keyAsString(f), tjf(f : V) : JValue) :: Nil | |
} | |
} | |
object Test { | |
def main(args: Array[String]) { | |
val x = ("a" ->> 1) :: | |
("b" ->> "c") :: HNil | |
val y = toJSON.recordToJSON(x) // wookie | |
println(JSON.pretty(y)) | |
val z = toJSON(x) // no wookie | |
println(JSON.pretty(z)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment