Java code
Public class JsonTool {
/**
* Json string formatting
*
* @ Param json
* @ Param fillStringUnit
* @ Return
*/
Public static String formatJson (String json, String fillStringUnit ){
If (json = null | json. trim (). length () = 0 ){
Return null;
}
Int fixedLenth = 0;
ArrayList <String> tokenList = new ArrayList <String> ();
{
String jsonTemp = json;
// Pre-read
While (jsonTemp. length ()> 0 ){
String token = getToken (jsonTemp );
JsonTemp = jsonTemp. substring (token. length ());
Token = token. trim ();
TokenList. add (token );
}
}
For (int I = 0; I <tokenList. size (); I ++ ){
String token = tokenList. get (I );
Int length = token. getBytes (). length;
If (length> fixedLenth & I <tokenList. size ()-1 & tokenList. get (I + 1). equals (":")){
FixedLenth = length;
}
}
StringBuilder buf = new StringBuilder ();
Int count = 0;
For (int I = 0; I <tokenList. size (); I ++ ){
String token = tokenList. get (I );
If (token. equals (",")){
Buf. append (token );
DoFill (buf, count, fillStringUnit );
Continue;
}
If (token. equals (":")){
Buf. append (""). append (token). append ("");
Continue;
}
If (token. equals ("{")){
String nextToken = tokenList. get (I + 1 );
If (nextToken. equals ("}")){
I ++;
Buf. append ("{}");
} Else {
Count ++;
Buf. append (token );
DoFill (buf, count, fillStringUnit );
}
Continue;
}
If (token. equals ("}")){
Count --;
DoFill (buf, count, fillStringUnit );
Buf. append (token );
Continue;
}
If (token. equals ("[")){
String nextToken = tokenList. get (I + 1 );
If (nextToken. equals ("]") {
I ++;
Buf. append ("[]");
} Else {
Count ++;
Buf. append (token );
DoFill (buf, count, fillStringUnit );
}
Continue;
}
If (token. equals ("]") {
Count --;
DoFill (buf, count, fillStringUnit );
Buf. append (token );
Continue;
}
Buf. append (token );
// Align left
If (I <tokenList. size ()-1 & tokenList. get (I + 1). equals (":")){
Int fillLength = fixedLenth-token. getBytes (). length;
If (fillLength> 0 ){
For (int j = 0; j <fillLength; j ++ ){
Buf. append ("");
}
}
}
}
Return buf. toString ();
}
Private static String getToken (String json ){
StringBuilder buf = new StringBuilder ();
Boolean isInYinHao = false;
While (json. length ()> 0 ){
String token = json. substring (0, 1 );
Json = json. substring (1 );
If (! IsInYinHao &&
(Token. equals (":") | token. equals ("{") | token. equals ("}")
| Token. equals ("[") | token. equals ("]")
| Token. equals (","))){
If (buf. toString (). trim (). length () = 0 ){
Buf. append (token );
}
Break;
}
If (token. equals ("\\")){
Buf. append (token );
Buf. append (json. substring (0, 1 ));
Json = json. substring (1 );
Continue;
}
If (token. equals ("\"")){
Buf. append (token );
If (isInYinHao ){
Break;
} Else {
IsInYinHao = true;
Continue;
}
}
Buf. append (token );
}
Return buf. toString ();
}
Private static void doFill (StringBuilder buf, int count, String fillStringUnit ){
Buf. append ("\ n ");
For (int I = 0; I <count; I ++ ){
Buf. append (fillStringUnit );
}
}
}
Author: "wuyuhou"