Last active
June 6, 2018 23:54
-
-
Save naderz/ba58493c20eab112c7db2ae4aaacd776 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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