json4s: Convert type to JValue
Asked Answered
T

1

16

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

Trichina answered 28/4, 2014 at 18:23 Comment(0)
T
14

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)
}
Trichina answered 28/4, 2014 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.