Is there a way to pretty print arbitrary JSON with...
# serialization
m
Is there a way to pretty print arbitrary JSON with kotlinx.serialisation? I have a String with some JSON, I want to format it into a formatted String to pretty print. I don't care about the content of the JSON, it can be anything. In GSON, this is achieved with:
JsonParser.parse
to parse any JSON and then
gson.toJson(parsed)
, to print, with the GSON instance using pretty printing. In kotlinx.serialisation, we can also parse arbitrary JSON with
json.parseToJsonElement
, and then print it with
JsonElement.toString()
. But the printing doesn't use the
Json
instance and so doesn't use the pretty-printing setting that is enabled on it.
v
I guess
Copy code
val json = Json { prettyPrint = true }
val prettyPrinted = json.encodeToString(json.parseToJsonElement("{ my: json }"))
m
Ah,
JsonElement
can be passed to
encodeToString
, I didn't realize that.
v
I didn't try, but that's my guess 🙂
m
Can confirm it works, thank you.
👌 1
f
For anyone else that found this thread through search: you'll need to import the extension function
kotlinx.serialization.encodeToString
in order for this to work 👍