Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json4s: Convert type to JValue

Tags:

scala

json4s

I have some source object src and would like to get a JValue from it. All the examples and documentation for json4s seem to revolve around getting a JSON-encoded string, like so:

def encodeJson(src: AnyRef): String = {
    import org.json4s.NoTypeHints
    import org.json4s.JsonDSL.WithDouble._
    import org.json4s.jackson.JsonMethods._
    import org.json4s.jackson.Serialization
    import org.json4s.jackson.Serialization.write
    implicit val formats = Serialization.formats(NoTypeHints)

    write(src)
}

That's great if I only want the end result, but I'd prefer to write a:

def encodeJson(src: AnyRef): JValue

It seems like ToJsonWritable[T] is what I want to use, but I can't seem to find an implementation for Writer[AnyRef] (nor can I find scaladocs for json4s which would just tell me the implementations).

like image 278
Travis Gockel Avatar asked Apr 28 '14 18:04

Travis Gockel


1 Answers

The answer here is org.json4s.Extraction -- it has a method decompose(a: Any)(implicit formats: Formats): JValue:

def encodeJson(src: AnyRef): JValue = {
    import org.json4s.{ Extraction, NoTypeHints }
    import org.json4s.JsonDSL.WithDouble._
    import org.json4s.jackson.Serialization
    implicit val formats = Serialization.formats(NoTypeHints)

    Extraction.decompose(src)
}
like image 141
Travis Gockel Avatar answered Sep 26 '22 05:09

Travis Gockel