Skip to content

Instantly share code, notes, and snippets.

@xnuk
Last active February 1, 2024 23:47
Show Gist options
  • Save xnuk/53865e8cd568e355e12ce5db2122f11d to your computer and use it in GitHub Desktop.
Save xnuk/53865e8cd568e355e12ce5db2122f11d to your computer and use it in GitHub Desktop.
Java Serialized HashMap<String, String | Boolean> --> JSON
// $ kotlinc-jvm -include-runtime -d parser.jar parser.kt
// $ java -jar parser.jar
import java.io.Serializable
import java.io.ObjectInputStream
import java.io.FileInputStream
import java.util.HashMap
// simple, and wrong escaping for JSON
fun escapeStr(s: String): String =
'"' +
s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") +
'"'
fun main() {
FileInputStream("./input-file").use { fis ->
ObjectInputStream(fis).use { ois ->
val map = ois.readObject()
if (map !is HashMap<*, *>) return
var first = true
for ((key, value) in map) {
if (key !is String) return
val escapedKey = escapeStr(key)
val prefix = if (first) { '{' } else { ',' }
when (value) {
is String -> {
println("${prefix} $escapedKey: ${escapeStr(value)}")
}
is Boolean -> {
println("${prefix} $escapedKey: $value")
}
}
first = false
}
println('}')
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment