-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9f9c73f
commit 1a22c76
Showing
2 changed files
with
71 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
src/jvmMain/kotlin/com/sunnychung/application/multiplatform/hellohttp/parser/JsonParser.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package com.sunnychung.application.multiplatform.hellohttp.parser | ||
|
||
import com.fasterxml.jackson.databind.JsonNode | ||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper | ||
|
||
class JsonParser(jsonBytes: ByteArray) { | ||
val tree = jacksonObjectMapper().readTree(jsonBytes) | ||
|
||
constructor(json: String) : this(json.encodeToByteArray()) | ||
|
||
fun prettify(): String { | ||
return buildString { | ||
fun indent(level: Int) { | ||
if (level > 0) { | ||
append(" ".repeat(2 * level)) | ||
} | ||
} | ||
|
||
fun StringBuilder.transverse(node: JsonNode, indentLevel: Int) { | ||
if (node.isArray) { | ||
append('[') | ||
if (node.size() <= 20 && node.all { it.isValueNode }) { | ||
node.forEachIndexed { i, it -> | ||
if (i > 0) { | ||
append(", ") | ||
} | ||
transverse(it, 0) | ||
} | ||
} else { | ||
append("\n") | ||
node.forEachIndexed { i, it -> | ||
if (i > 0) { | ||
append(",\n") | ||
} | ||
indent(indentLevel + 1) | ||
transverse(it, indentLevel + 1) | ||
} | ||
append("\n") | ||
indent(indentLevel) | ||
} | ||
append(']') | ||
} else if (node.isObject) { | ||
if (node.isEmpty) { | ||
append("{}") | ||
} else { | ||
append("{\n") | ||
node.fields().withIndex().forEach { (i, it) -> | ||
if (i > 0) { | ||
append(",\n") | ||
} | ||
indent(indentLevel + 1) | ||
append("\"${it.key}\": ") | ||
transverse(it.value, indentLevel + 1) | ||
} | ||
append("\n") | ||
indent(indentLevel) | ||
append('}') | ||
} | ||
} else if (node.isValueNode) { | ||
append(node.toPrettyString()) | ||
} else { | ||
throw RuntimeException("what is this? -- $node") | ||
} | ||
} | ||
|
||
transverse(tree, 0) | ||
} | ||
} | ||
} |