How to display JSON response string with formatting something similar to https://jsonformatter.org/json-parser
?
For example: How to display following code in textview ?
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
P.S: Preferably color formatted.
In short ..
1.How to format and display JSON string ?
2.How to format and display Java code ?
I wrote the following utility method to format and indent (no colors yet):
public static String formatString(String text){
StringBuilder json = new StringBuilder();
String indentString = "";
for (int i = 0; i < text.length(); i++) {
char letter = text.charAt(i);
switch (letter) {
case '{':
case '[':
json.append("\n" + indentString + letter + "\n");
indentString = indentString + "\t";
json.append(indentString);
break;
case '}':
case ']':
indentString = indentString.replaceFirst("\t", "");
json.append("\n" + indentString + letter);
break;
case ',':
json.append(letter + "\n" + indentString);
break;
default:
json.append(letter);
break;
}
}
return json.toString();
}