62,616
社区成员
发帖
与我相关
我的任务
分享
import java.util.*;
public class JsonParser {
public static void parse(String json) {
LinkedList<String> currentNodeList = new LinkedList<String>();
String currentNode = "$";
StringBuffer currentStr = new StringBuffer();
List<String> result = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
switch (c) {
case '{':
currentNodeList.add(currentNode);
break;
case '}':
currentNodeList.removeLast();
break;
case ':':
currentNode = getCurrentNodeStr(currentStr);
currentStr = new StringBuffer();
result.add(getParentStr(currentNodeList) + currentNode);
break;
default:
currentStr.append(c);
break;
}
}
for(String node:result) {
System.out.println(node);
}
}
public static String getCurrentNodeStr(StringBuffer currentStr) {
String temp = currentStr.substring(0, currentStr.lastIndexOf("\""));
temp = temp.substring(temp.lastIndexOf("\"") + 1);
return temp;
}
public static String getParentStr(List<String> parentList) {
StringBuffer result = new StringBuffer();
for(String node:parentList) {
result.append(node);
result.append(".");
}
return result.toString();
}
public static void main(String[] args) {
String json = "{\"pwd\":\"1\",\"b\":\"3\",\"account\":{\"root\":{\"j\":\"5\"}},\"data\":[{\"127.0.0.1\":{\"root\":\"aa\"},\"127.0.0.2\":{}}],\"code\":\"200\",\"msg\":\"成功\"}";
parse(json);
}
}