快放假了上班没啥事,参考https://segmentfault.com/a/1190000038551193摸了个json解析
public class JsonParser {
// json文本
private char[] source;
// 当前解析到的位置
private int i;
// 当前需要解析的字符
private char ch;
private static JsonParser parser;
public static JsonParser getInstance() {
if (parser == null) {
parser = new JsonParser();
}
return parser;
}
public static Object parse(String json) {
parser = getInstance();
parser.init(json);
return parser.parse();
}
private void init(String json) {
json += " ";
this.source = json.toCharArray();
this.i = -1;
this.ch = ' ';
}
private char next(char... expected) {
if (expected.length > 0 && expected[0] != ch) {
throw new RuntimeException(String.format("期望是: '%s', 实际上是: '%s'", expected[0], ch));
}
ch = source[++i];
return ch;
}
private void skipWhite() {
while (ch == '\n' || ch == '\t' || ch == ' ') {
next();
}
}
public Object parse() {
skipWhite();
switch (ch) {
case '{':
return parseObject();
case '"':
return parseString();
case '[':
return parseArray();
case '-':
return parseNumber();
default:
return ch >= '0' && ch <= '9' ? parseNumber() : parseBoolAndNull();
}
}
private Object parseBoolAndNull() {
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
}
throw new RuntimeException("解析bool或是null异常");
}
// "k": 10, "k2": -10.5
private BigDecimal parseNumber() {
String number = "";
// 负数
if (ch == '-') {
next('-');
number += "-";
}
while (ch >= '0' && ch <= '9') {
number += ch;
next();
}
// 小数
if (ch == '.') {
next('.');
number += '.';
while (ch >= '0' && ch <= '9') {
number += ch;
next();
}
}
return new BigDecimal(number);
}
// [xx, xx, xx]
private List<Object> parseArray() {
List<Object> list = new ArrayList<>();
next('[');
skipWhite();
if (ch == ']') {
next(']');
return list;
}
while (i < source.length) {
// 解析元素
list.add(parse());
skipWhite();
if (ch == ']') {
next(']');
return list;
}
next(',');
skipWhite();
}
throw new RuntimeException("解析array异常");
}
// 此时 ch为第一个"
// 解析 "..." 之间的内容
private String parseString() {
next('"');
String str = "";
while (ch != '"') {
str += ch;
next();
}
next('"');
return str;
}
private Map<String, Object> parseObject() {
Map<String, Object> result = new HashMap<>();
next('{');
skipWhite();
// 空json {}
if (ch == '}') {
next('}');
return new HashMap<>();
}
while (i < source.length) {
// 解析key
String key = parseString();
skipWhite();
next(':');
// 冒号后面不确定是啥
result.put(key, parse());
skipWhite();
if (ch == '}') {
next('}');
return result;
}
next(',');
skipWhite();
}
throw new RuntimeException("解析object异常");
}
public static void print(Object result, String skip) {
if (result instanceof Map) {
Map<String, Object> map = (Map<String, Object>) result;
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.print(skip + entry.getKey() + ": \n");
print(entry.getValue(), skip + "=====");
}
} else if (result instanceof List) {
List<Object> list = (List<Object>) result;
for (Object o : list) {
print(o, skip);
}
} else {
System.out.println(skip + result);
}
}
public static void main(String[] args) {
String json = "{\"k1\" : \"zz\", \"k2\" : {\"kk1\": 10.5, \"kk2\": -9.9}, \"k3\": [614, \"b\", {\"kkk1\": \"nanase\", \"kkk2\": true, \"kkk3\": false, \"kkk4\": null, \"kkkk5\": []}]}";
Object result = JsonParser.parse(json);
System.out.println(result);
JsonParser.print(result, "");
}
}