public
class
JsonPrettifier {
public
static
String prettifyJson(String jsonInput) {
int
indent =
0
;
StringBuilder result =
new
StringBuilder();
for
(
char
x : jsonInput.toCharArray()) {
if
(x ==
'{'
) {
indent +=
2
;
result.append(x);
result.append(
'\n'
);
result.append(
" "
.repeat(Math.max(
0
, indent)));
}
else
if
(x ==
'['
) {
result.append(
'\n'
);
result.append(
" "
.repeat(Math.max(
0
, indent)));
indent +=
2
;
result.append(x);
result.append(
'\n'
);
result.append(
" "
.repeat(Math.max(
0
, indent)));
}
else
if
(x ==
'}'
|| x ==
']'
) {
indent -=
2
;
result.append(
'\n'
);
result.append(
" "
.repeat(Math.max(
0
, indent)));
result.append(x);
}
else
if
(x ==
','
) {
result.append(x);
result.append(
'\n'
);
result.append(
" "
.repeat(Math.max(
0
, indent)));
}
else
{
result.append(x);
}
}
return
result.toString();
}
/**
* Main method to demonstrate JSON prettifying.
*/
public
static
void
main(String[] args) {
String jsonInput =
"{\"username\":\"Jonas\",\"devices\":[\"iPhone 13 Pro\",\"Samsung Galaxy S30\"]}"
;
String prettified = prettifyJson(jsonInput);
System.out.println(prettified);
}
}