闲来无事,写一段代码,格式json字符串,不是解析奥,只是让json看起来更规整一些。
package com.sortworld;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class JsonFormat {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new FileReader(new File("E://h")));
String jsons = "", str;
while ((str = br.readLine()) != null) {
jsons += str;
}
br.close();
System.out.println(format(jsons, 0));
}
private static Stack stack = new Stack();
public static String format(String json, int depth) {
String result = "";
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '[')
stack.push(i);
if (c == ']') {
int popTag = stack.pop();
if (stack.isEmpty()) {
String childJson = json.substring(popTag + 1, i);
// 递归解析数组
result += "[" + format(childJson, depth + 2)
+ tokenStr(depth) + "";
}
}
if (stack.isEmpty()) {
String token = getToken(c, depth, json, i);
result += token;
}
}
return result;
}
//
private static String getToken(char c, int depth, String json, int i) {
if (c == '{' || c == '}')
return "\n" + tokenStr(depth + 1) + c + "\n" + tokenStr(depth + 2);
if (c == ',' && json.charAt(i + 1) == '\"')
return c + "\n" + tokenStr(depth + 2);
if (c == ']')
return "\n" + tokenStr(depth + 2) + c + "\n" + tokenStr(depth + 2);
return c + "";
}
// 分隔符
private static String tokenStr(int depth) {
String token = "";
for (int i = 0; i < depth; i++)
token += " ";
return token;
}
}
测试用例
{"count":1,"distance":0,"result":[{"deadLineTime":"2000-01-01 00:00:00","districtId":14768},{"deadLineTime":"2000-01-01 00:00:00"}],"time":2} 测试结果
{
"count":1,
"distance":0,
"result":[
{
"deadLineTime":"2000-01-01 00:00:00",
"districtId":14768
}
,
{
"deadLineTime":"2000-01-01 00:00:00"
}
]
,
"time":2
}