【问题标题】:How do I generate pretty JSON with json4s?如何使用 json4s 生成漂亮的 JSON?
【发布时间】:2016-12-31 19:25:07
【问题描述】:

这段 sn-p 代码运行良好,但它会生成紧凑的 JSON(没有换行符/人类可读性不强)。

import org.json4s.native.Serialization.write
implicit val jsonFormats = DefaultFormats

//snapshotList is a case class
val jsonString: String = write(snapshotList)

有没有一种简单的方法可以从中生成漂亮的 JSON?

我有这个解决方法,但我想知道是否存在更有效的方法:

import org.json4s.jackson.JsonMethods._
val prettyJsonString = pretty(render(parse(jsonString)))

【问题讨论】:

    标签: scala json4s


    【解决方案1】:
    import org.json4s.jackson.Serialization.writePretty
    
    val jsonString: String = writePretty(snapshotList)
    

    【讨论】:

    • 对我来说导入语句应该是:import org.json4s.jackson.Serialization.writePretty
    【解决方案2】:

    您可以使用 ObjectMapper writerWithDefaultPrettyPrinter function:

    ObjectMapper mapper = new ObjectMapper();
    val pretty = mapper.writerWithDefaultPrettyPrinter()
                       .writeValueAsString(jsonString));
    

    这将返回一个ObjectWriter 对象,您可以从中获取格式精美的字符串。

    【讨论】:

    • 我尝试了这种方法,但我遇到了一个异常:java.lang.ClassCastException: com.fasterxml.jackson.databind.ObjectWriter cannot be cast to scala.runtime.Nothing$ 你知道为什么吗?这很奇怪,因为我查看了 pretty() 方法的源代码,它基本上完全按照您的建议进行。
    • 这是我的测试代码:import com.fasterxml.jackson.databind.ObjectMapperimport org.json4s._import org.json4s.jackson.JsonMethods._val jsonString = """{"price": 10.8}"""val json = parse(jsonString)val mapper = new ObjectMapper()mapper.writeValueAsString(json) //this worksval writer = mapper.writerWithDefaultPrettyPrinter() //this throws exceptionval prettyJsonString = writer.writeValueAsString(json)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多