Question

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).

Was it helpful?

Solution

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)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top