json4s: Convert type to JValue

走远了吗. 提交于 2019-12-03 17:30:34

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/23348480/json4s-convert-type-to-jvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!