How to set formatted JSON response string in a TextView?
The method @suhas_sm suggested is great, but fails to indent correctly if there's a key or a value that contains one of the special characters, "{" for example.
My solution (based on suhas_sm's method):
public static String formatString(String text){
StringBuilder json = new StringBuilder();
String indentString = "";
boolean inQuotes = false;
boolean isEscaped = false;
for (int i = 0; i < text.length(); i++) {
char letter = text.charAt(i);
switch (letter) {
case '\\':
isEscaped = !isEscaped;
break;
case '"':
if (!isEscaped) {
inQuotes = !inQuotes;
}
break;
default:
isEscaped = false;
break;
}
if (!inQuotes && !isEscaped) {
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;
}
} else {
json.append(letter);
}
}
return json.toString();
}
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();
}
Do you want to parse it or simply show the raw JSON response? If the former:
How to parse JSON in Android
If you want it to be formatted, you can do it manually:
example:
{"J":5,"0":"N"}
first remove "{,}", split this array '"J":5,"0":"N"' by ',' and then for the colouring just check if a value has quotations marks or not and choose accordingly. Just a simple string manipulation.
Then output:
- {
- foreach loop of the array items with colouring
- }
Much simpler approch, there is a toString
method with indent space param for JSONObject
,
can be used like this :
JSONObject jsonObject = new JSONObject(jsonString);
textView.setText(jsonObject.toString(4));// 4 is number of spaces for indent
same is applicable for JSONArray
reference :
https://developer.android.com/reference/org/json/JSONObject#toString(int)
https://alvinalexander.com/android/android-json-print-json-string-human-readable-format-debugging