6

This snippet of code works very well, but it generates compact JSON (no line breaks / not very human readable).

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

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

Is there an easy way to generate pretty JSON from this?

I have this workaround but I'm wondering if a more efficient way exists:

import org.json4s.jackson.JsonMethods._
val prettyJsonString = pretty(render(parse(jsonString)))
arosca
  • 469
  • 7
  • 15

2 Answers2

15
import org.json4s.jackson.Serialization.writePretty

val jsonString: String = writePretty(snapshotList)
ibaralf
  • 12,218
  • 5
  • 47
  • 69
Michael Pollmeier
  • 1,370
  • 11
  • 20
  • 2
    For me import statement should've been: `import org.json4s.jackson.Serialization.writePretty` – zbstof Nov 15 '19 at 10:22
0

You can use the ObjectMapper writerWithDefaultPrettyPrinter function:

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

This returns a ObjectWriter object from which you can get a pretty-formatted string.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • I tried this approach but I'm getting an exception: `java.lang.ClassCastException: com.fasterxml.jackson.databind.ObjectWriter cannot be cast to scala.runtime.Nothing$` Do you know why? It's strange because I looked at the source code of the pretty() method and it does basically exactly what you suggested. – arosca Aug 29 '16 at 13:27
  • Here's my test code: `import com.fasterxml.jackson.databind.ObjectMapper` `import org.json4s._` `import org.json4s.jackson.JsonMethods._` `val jsonString = """{"price": 10.8}"""` `val json = parse(jsonString)` `val mapper = new ObjectMapper()` `mapper.writeValueAsString(json) //this works` `val writer = mapper.writerWithDefaultPrettyPrinter() //this throws exception` `val prettyJsonString = writer.writeValueAsString(json)` – arosca Aug 29 '16 at 13:27