json4s: Convert type to JValue

2020-06-01 10:20发布

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

标签: scala json4s
1条回答
闹够了就滚
2楼-- · 2020-06-01 10:59

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)
}
查看更多
登录 后发表回答