Hi, is it possible to specify custom `Composer` f...
# serialization
y
Hi, is it possible to specify custom
Composer
for
Json
configuration? I need to serialize objects with spaced format like
Copy code
data class Foo(val country: CountryCode)
->
{"country": "US"}
With Jackson I can specify
PrettyPrinter
Copy code
class SpacedPrettyPrinter : MinimalPrettyPrinter() {
    override fun writeArrayValueSeparator(g: JsonGenerator) = g.writeRaw(", ")
    override fun writeObjectFieldValueSeparator(g: JsonGenerator) = g.writeRaw(": ")
    override fun writeObjectEntrySeparator(g: JsonGenerator) = g.writeRaw(", ")
}
c
what is the requirement for having a space there? it’s still valid json, the whitespace is ignored.
y
There are only 2 options in Json configuration right now: • prettyPrint = true - it adds
\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.
Copy code
{
  "bar": "baz",
  "active": false,
  "balance": 7.77
}
c
Not seeing where space separators are required to be there.
jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys
Why does the format have to match, other than being valid json?
y
Yes, they are not required and I'm not saying there is any bug here. Let's just say my business logic requires to have specific serialization format. With Jackson it is possible with custom
PrettyPrint
class, I just want to know if such customization is possible with kotlin serialization:
Copy code
{
  "bar": "baz",
  "active": false,
  "balance": 7.77
}
a
aside from whether it's necessary or not, you could encode to a JsonElement
Copy code
val data = SomeData(...)
val json: JsonElement = Json.encodeToJsonElement(data)
and then create an extension function to encode it to a String
Copy code
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(':')
y
Got it, thanks