Skip to content

Instantly share code, notes, and snippets.

@naderz
Last active June 6, 2018 23:54
Show Gist options
  • Select an option

  • Save naderz/ba58493c20eab112c7db2ae4aaacd776 to your computer and use it in GitHub Desktop.

Select an option

Save naderz/ba58493c20eab112c7db2ae4aaacd776 to your computer and use it in GitHub Desktop.
class JsonUtil {
companion object {
fun findJson(mixedString: String): Pair<String, MutableList<String>> {
var mixed = mixedString
val jsons: MutableList<String> = ArrayList()
var first = mixed.indexOf('{')
while (first > -1) {
var last = mixed.lastIndexOf('}')
while (last > -1 && first > -1 && last > first) {
val bracesSubstring = mixed.substring(first, last + 1)
if (!bracesSubstring.isValidJson()) {
last--
continue
}
if (first + 1 != last)
jsons.add(bracesSubstring)
mixed = mixed.removeRange(first, last + 1)
//Start again
first = mixed.indexOf('{')
last = mixed.lastIndexOf('}')
}
if (first <= -1 || last <= -1) break else {
first = mixed.indexOf('{', first + 1)
}
}
return Pair(mixed, jsons)
}
fun String.isValidJson(): Boolean {
return try {
Gson().fromJson(this, JsonObject::class.java) != null
} catch (exc: Exception) {
false
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment