Yuri
08/30/2023, 4:10 PMComposer
for Json
configuration?
I need to serialize objects with spaced format like
data class Foo(val country: CountryCode)
->
{"country": "US"}
With Jackson I can specify PrettyPrinter
class SpacedPrettyPrinter : MinimalPrettyPrinter() {
override fun writeArrayValueSeparator(g: JsonGenerator) = g.writeRaw(", ")
override fun writeObjectFieldValueSeparator(g: JsonGenerator) = g.writeRaw(": ")
override fun writeObjectEntrySeparator(g: JsonGenerator) = g.writeRaw(", ")
}
Chris Lee
08/30/2023, 4:16 PMYuri
08/30/2023, 4:29 PM\n
• prettyPrint = false - it doesn't add any spaces
In my case I need to match the format returned from JSONB columns in Postgres (using Exposed),
which adds space separators.
{
"bar": "baz",
"active": false,
"balance": 7.77
}
Chris Lee
08/30/2023, 4:32 PMjsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keysWhy does the format have to match, other than being valid json?
Yuri
08/30/2023, 4:37 PMPrettyPrint
class, I just want to know if such customization is possible with kotlin serialization:
{
"bar": "baz",
"active": false,
"balance": 7.77
}
Adam S
08/30/2023, 4:39 PMval data = SomeData(...)
val json: JsonElement = Json.encodeToJsonElement(data)
and then create an extension function to encode it to a String
fun JsonElement.toJsonBString(): String {
return when (this) {
is JsonObject -> /*...*/
is JsonArray -> toString()
JsonNull -> toString()
is JsonPrimitive -> toString()
}
}
Everything apart from JsonObject is the same, and for JsonObject you'd have to re-implement the existing toString(), but use append(": ")
instead of append(':')
Yuri
08/30/2023, 4:49 PM