Skip to content

Instantly share code, notes, and snippets.

@henriquekano
Created June 6, 2022 00:55
Show Gist options
  • Save henriquekano/78355f2d9313d01e51ed40cf82a6b28e to your computer and use it in GitHub Desktop.
Save henriquekano/78355f2d9313d01e51ed40cf82a6b28e to your computer and use it in GitHub Desktop.
Android compose json viewer
@file:Suppress("UNCHECKED_CAST")
package com.kanohenrique.mytube.compose.components
import android.util.Log
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.withStyle
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.*
private enum class ParentType {
OBJECT,
ARRAY,
ROOT,
}
private data class JsonLevel(
val entries: List<Map.Entry<String, Any>>? = null,
val items: List<Any>? = null,
var index: Int,
val parentType: ParentType,
) {
val inObjectContext: Boolean
get() = entries != null
val inArrayContext: Boolean
get() = items != null
init {
require(
entries != null
|| items != null
)
}
}
private fun annotateJsonValue(
jsonValue: Map<String, Any>,
keysColor: Color,
): AnnotatedString {
val context: AnnotatedString.Builder = AnnotatedString.Builder()
val indentation = 4
fun appendGeneric(value: String, color: Color, level: Int = 0) {
val indentationSpaces = " ".repeat(level * indentation)
context.append(indentationSpaces)
context.withStyle(style = SpanStyle(color)) {
append(value)
}
}
fun appendStringValue(value: String) {
appendGeneric(
"\"$value\"\n",
Color.Green,
)
}
fun appendArrayStringValue(value: String, level: Int) {
appendGeneric(
"\"$value\"\n",
Color.Green,
level,
)
}
fun appendNumberValue(value: Number) {
appendGeneric(
"$value\n",
Color.Cyan,
)
}
fun appendBoolean(boolean: Boolean) {
appendGeneric(
"$boolean\n",
Color.Magenta,
)
}
fun appendArrayNumberValue(value: Number, level: Int) {
appendGeneric(
"$value\n",
Color.Green,
level,
)
}
fun appendOpenBracket(level: Int = 0) {
appendGeneric(
"{\n",
Color.LightGray,
if (level <= 0) 0 else level - 1,
)
}
fun appendCloseBracket(level: Int) {
appendGeneric(
"}\n",
Color.LightGray,
if (level <= 0) 0 else level - 1,
)
}
fun appendIndentedOpenSquareBracket(level: Int) {
appendGeneric(
"[\n",
Color.LightGray,
if (level <= 0) 0 else level - 1,
)
}
fun appendIndentedCloseSquareBracket(level: Int) {
appendGeneric(
"]\n",
Color.LightGray,
if (level <= 0) 0 else level - 1,
)
}
fun appendEmptyObject(level: Int = 0) {
appendGeneric(
"{}\n",
Color.LightGray,
level,
)
}
fun appendEmptyArray() {
appendGeneric(
"[]\n",
Color.LightGray,
)
}
fun appendKey(value: String, level: Int) {
appendGeneric(
"\"$value\": ",
keysColor,
level,
)
}
val stack = Stack<JsonLevel>()
stack.push(
JsonLevel(
entries = jsonValue.entries.toList(),
index = 0,
parentType = ParentType.ROOT,
)
)
mainLoop@while(stack.size > 0) {
val currentLevel = stack.lastElement()
val from = currentLevel.index
val level = stack.size
if (currentLevel.inObjectContext) {
Log.d(TAG, "object $currentLevel")
// opening and closing brackets
when {
currentLevel.entries!!.isEmpty() -> {
stack.pop()
if (currentLevel.parentType == ParentType.ARRAY) {
appendEmptyObject(level - 1)
} else {
appendEmptyObject()
}
continue@mainLoop
}
currentLevel.index == 0 -> {
if (currentLevel.parentType == ParentType.ARRAY) {
appendOpenBracket(level)
} else {
appendOpenBracket()
}
}
currentLevel.index == currentLevel.entries.size -> {
stack.pop()
appendCloseBracket(level)
continue@mainLoop
}
}
objectEntriesFor@ for(i in from until currentLevel.entries!!.size) {
val entry = currentLevel.entries[i]
val key = entry.key
val value = entry.value
currentLevel.index++
appendKey(key, level)
when (value) {
// entering an object
is Map<*, *> -> {
stack.add(JsonLevel(
index = 0,
entries = (value as Map<String, Any>).entries.toList(),
parentType = ParentType.OBJECT,
))
break@objectEntriesFor
}
// entering a list
is List<*> -> {
stack.add(JsonLevel(
index = 0,
items = (value as List<Any>),
parentType = ParentType.OBJECT,
))
break@objectEntriesFor
}
// it's a primitive!
else -> {
when(value) {
is String -> {
appendStringValue(value)
}
is Number -> {
appendNumberValue(value)
}
is Boolean -> {
appendBoolean(value)
}
else -> throw Exception("Should not happen. Value: $value")
}
}
}
}
}
if (currentLevel.inArrayContext) {
Log.d(TAG, "array ${currentLevel}")
// opening and closing square brackets
when {
currentLevel.items!!.isEmpty() -> {
stack.pop()
appendEmptyArray()
continue@mainLoop
}
currentLevel.index == 0 -> {
appendIndentedOpenSquareBracket(
level = if (currentLevel.parentType in listOf(ParentType.OBJECT, ParentType.ROOT)) {
0
} else {
level
}
)
}
currentLevel.index == currentLevel.items.size -> {
stack.pop()
appendIndentedCloseSquareBracket(level)
continue@mainLoop
}
}
objectEntriesFor@ for(i in from until currentLevel.items!!.size) {
val value = currentLevel.items[i]
currentLevel.index++
when (value) {
// entering an object
is Map<*, *> -> {
stack.add(JsonLevel(
index = 0,
entries = (value as Map<String, Any>).entries.toList(),
parentType = ParentType.ARRAY,
))
break@objectEntriesFor
}
// entering a list
is List<*> -> {
stack.add(JsonLevel(
index = 0,
items = (value as List<Any>),
parentType = ParentType.ARRAY,
))
break@objectEntriesFor
}
// it's a primitive!
else -> {
when(value) {
is String -> {
appendArrayStringValue(value, level)
}
is Number -> {
appendArrayNumberValue(value, level)
}
else -> throw Exception("Should not happen")
}
}
}
}
}
}
return context.toAnnotatedString()
}
private const val TAG = "JsonViewer"
@Composable
fun JsonViewer(
jsonValue: String,
) {
val keysColor = MaterialTheme.colors.onBackground
val parsedJson = remember(jsonValue) {
val gson = Gson()
val value = gson.fromJson<Map<String, Any>>(jsonValue, object : TypeToken<Map<String, Any>>(){}.type)
annotateJsonValue(
value,
keysColor = keysColor,
)
}
Log.d(TAG, parsedJson.toString())
Text(
parsedJson
)
}
@henriquekano
Copy link
Author

henriquekano commented Jun 6, 2022

Since I didn't find any json viewer for android compose, there we go. It's not the prettiest, but since I did it in like 3 hours or so, LGTM.
It just indents and highlight stuff. No commas are present in the result for simplicity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment