Skip to content

Instantly share code, notes, and snippets.

@utkuozdemir
Last active October 27, 2022 07:45
Show Gist options
  • Save utkuozdemir/43f66010f5b2e70cbc4e7be1a16ccd91 to your computer and use it in GitHub Desktop.
Save utkuozdemir/43f66010f5b2e70cbc4e7be1a16ccd91 to your computer and use it in GitHub Desktop.
Kotlin + Jackson Pretty Print Override
package org.utkuozdemir.json
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.core.util.Separators
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Test
data class Person(val name: String, val age: Int)
class CustomPrettyPrinter : DefaultPrettyPrinter() {
override fun createInstance(): CustomPrettyPrinter {
return CustomPrettyPrinter()
}
override fun withSeparators(separators: Separators?): CustomPrettyPrinter {
super.withSeparators(separators)
_objectFieldValueSeparatorWithSpaces = _objectFieldValueSeparatorWithSpaces.trimStart()
return this
}
}
class JsonTest {
@Test
fun testJson() {
val objectMapper = ObjectMapper()
val prettyPrinter = CustomPrettyPrinter()
objectMapper.setDefaultPrettyPrinter(prettyPrinter)
val json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(Person("Utku", 33))
println(json)
}
}
@utkuozdemir
Copy link
Author

utkuozdemir commented Oct 26, 2022

Removes the trailing space on field value separator from the Jackson pretty printer, so the fields print like "foo": "bar" instead of "foo" : "bar".

The code above outputs:

{
  "name": "Utku",
  "age": 33
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment