漂亮地打印一个 Kotlin Json Serializable。

huangapple go评论62阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2023年7月20日 09:25:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定