Last active
October 27, 2022 07:45
-
-
Save utkuozdemir/43f66010f5b2e70cbc4e7be1a16ccd91 to your computer and use it in GitHub Desktop.
Kotlin + Jackson Pretty Print Override
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: