英文:
Pretty print a Kotlin Json Serializable
问题
如何在 Kotlin 可序列化类中进行漂亮的打印,使键以单独的行格式化,而不是在一行上(默认方式)?Json.encodeToString
将所有内容打印在一行上。我在 kotlinx-serialization-json 库中看到了 prettyPrint 文档,但是 JsonBuilder 和 JsonConfiguration 具有私有构造函数。
示例可序列化类:
@kotlinx.serialization.Serializable
data class MyObject(
val name: String,
val age: Int
)
val myObject = MyObject(name = "hello", age = 2)
val string = Json.encodeToString(myObject)
print(string)
上述代码会打印出 {"name":"hello","age":2}
,但我希望所有内容都在单独的行上。
英文:
How do you pretty print a Kotlin Serializable class so the keys are formatted on separate lines, and not on one line (the default)? Json.encodeToString
prints everything on one line. I see the prettyPrint documentation in the kotlinx-serialization-json library but the JsonBuilder and JsonConfiguration have private constructors.
Example serializable:
@kotlinx.serialization.Serializable
data class MyObject(
val name: String,
val age: Int
)
val myObject = MyObject(name = "hello", age = 2)
val string = Json.encodeToString(myObject)
print(string)
The above prints {"name":"hello","age":2}
but I want everything to be on separate lines.
答案1
得分: 1
Using this will give access to the JsonBuilder printing options.
val prettyJson = Json { // this returns the JsonBuilder
prettyPrint = true
// optional: specify indent
prettyPrintIndent = " "
}
val myObject = MyObject(name = "hello", age = 2)
val string = prettyJson.encodeToString(myObject)
print(string)
This prints:
{
"name": "hello",
"age": 2
}
英文:
Using this will give access to the JsonBuilder printing options.
val prettyJson = Json { // this returns the JsonBuilder
prettyPrint = true
// optional: specify indent
prettyPrintIndent = " "
}
val myObject = MyObject(name = "hello", age = 2)
val string = prettyJson.encodeToString(myObject)
print(string)
This prints:
{
"name": "hello",
"age": 2
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论