package java2.format;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fhqplzj on 17-2-23 at 下午12:08.
*/
public class PrettyJSON {
public static List<String> formatJSON(String s) {
s = StringUtils.stripToEmpty(s);
ArrayList<String> result = Lists.newArrayList();
int level = 0;
StringBuilder stringBuilder = new StringBuilder();
for (char c : s.toCharArray()) {
if (stringBuilder.length() > 0 && stringBuilder.charAt(stringBuilder.length() - 1) == '\n') {
stringBuilder.append(Strings.repeat("\t", level));
/*去掉每一行开头的空白符*/
if (StringUtils.isBlank(Character.toString(c))) {
continue;
}
}
switch (c) {
case '[':
case '{':
stringBuilder.append(c).append('\n');
level++;
break;
case ',':
stringBuilder.append(c).append('\n');
break;
case ']':
case '}':
stringBuilder.append('\n').append(Strings.repeat("\t", --level)).append(c);
if (level == 0) {
result.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
break;
default:
stringBuilder.append(c);
}
}
return result;
}
public static List<String> formatJSON(File file) {
String s = null;
try {
s = FileUtils.readFileToString(file, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
return formatJSON(s);
}
public static void main(String[] args) throws IOException {
List<String> result = formatJSON(new File("/tmp/json.txt"));
for (int i = 0; i < result.size(); i++) {
System.out.println(String.format("case %d:", i + 1));
System.out.println(StringUtils.stripToEmpty(result.get(i)));
}
}
}
完美打印JSON
最新推荐文章于 2024-03-07 10:41:53 发布