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 ?
How to format JSON string in JavaScript? How to format JSON string in JavaScript? To format HSON string in JavaScript, use JSON.stringify () with some parameters. Following is the code − To run the above program, you need to use the following command −
In this example, you will learn how to format the JSON String using Jackson's Pretty Print feature. It's easy to format JSON text, all you need to do is instead of just calling writeValueAsString () you need to first get defaultPrettyPrintWrite and then call writeValueAsString () method on that object.
It has the HTTP method-specific handler methods. A normal Spring controller is used to retrieve the responses from the ‘RestTemplate’ method and returns a view. This component retrieves the JSON data from the specified URL targeting REST API. Retrieved data is stored in a variable.
Formatted output not only stands out in logs but also they are easier to read but there is one drawback also. You cannot grep them in one line, you need to use the grep command with a context option to grep a couple of lines around matching to see full JSON output.
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With