-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpretty-print.java
More file actions
22 lines (21 loc) · 1.02 KB
/
pretty-print.java
File metadata and controls
22 lines (21 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {
String json = "{\"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\":{\"batter\":[{ \"id\": \"1001\", \"type\": \"Regular\" },{ \"id\": \"1002\", \"type\": \"Chocolate\" }]},\"topping\":[{ \"id\": \"5001\", \"type\": \"None\" },{ \"id\": \"5002\", \"type\": \"Glazed\" }]}";
System.out.println(pretty(json));
}
public static String pretty(String s) {
StringBuilder sb = new StringBuilder();
int indent = 0;
char pre = 0;
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) continue;
if (c == ']' || c == '}') indent--;
if (pre == '[' || pre == '{' || pre == ',' || c == ']' || c == '}') {
sb.append('\n');
for (int i = 0; i < indent; i++) sb.append(" ");
}
sb.append(c);
if (c == '[' || c == '{') indent++;
pre = c;
}
return sb.toString();
}