如何使用 json4s 生成漂亮的 JSON?

How do I generate pretty JSON with json4s?

这段代码效果很好,但生成的代码紧凑 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)))

您可以使用 ObjectMapper writerWithDefaultPrettyPrinter function:

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

这个 returns 一个 ObjectWriter 对象,您可以从中获取格式良好的字符串。

import org.json4s.jackson.Serialization.writePretty

val jsonString: String = writePretty(snapshotList)