privatestatic String transString(String text){ StringBuilder val = new StringBuilder(); for (int i = 1; i < text.length() - 1; i++) { if (text.charAt(i) != '\\') { val.append(text.charAt(i)); } else { switch (text.charAt(i + 1)) { case'n': val.append('\n'); break; case't': val.append('\t'); break; default: val.append(text.charAt(i + 1)); break; } i++; } } return val.toString(); }
privatestatic TokensParseResult parseTokens(List<Token> tokens, int index)throws Exception { switch (tokens.get(index).type) { case OBJECT_OPEN: { index++; Map<String, Object> data = new HashMap<>(); while (tokens.get(index).type != TokenType.OBJECT_CLOSE) { if (tokens.get(index).type == TokenType.STRING && tokens.get(index + 1).type == TokenType.COLON) { TokensParseResult item = parseTokens(tokens, index + 2); data.put(transString(tokens.get(index).value), item.data); index = item.nextIndex; if (tokens.get(index).type == TokenType.SPLIT) { index++; } } else { thrownew Exception(); } } returnnew TokensParseResult(data, index + 1); } case ARRAY_OPEN: { index++; List<Object> data = new ArrayList<>(); while (tokens.get(index).type != TokenType.ARRAY_CLOSE) { TokensParseResult item = parseTokens(tokens, index); data.add(item.data); index = item.nextIndex; if (tokens.get(index).type == TokenType.SPLIT) { index++; } } returnnew TokensParseResult(data, index + 1);
} case STRING: returnnew TokensParseResult(transString(tokens.get(index).value), index + 1); case NUMBER: returnnew TokensParseResult(Double.parseDouble(tokens.get(index).value), index + 1); case BOOLEAN: returnnew TokensParseResult(Boolean.parseBoolean(tokens.get(index).value), index + 1); case NULL: returnnew TokensParseResult(null, index + 1); default: thrownew Exception(); } }
privatestatic String enter(int depth){ StringBuilder val = new StringBuilder("\n"); for (int i = 0; i < depth; i++) { val.append(" "); } return val.toString(); }
privatestatic String formatTokens(List<Token> tokens){ StringBuilder format = new StringBuilder(); int depth = 0; for (Token token : tokens) { if (token.type == TokenType.OBJECT_CLOSE || token.type == TokenType.ARRAY_CLOSE) { format.append(enter(--depth)); } format.append(token.value); if (token.type == TokenType.OBJECT_OPEN || token.type == TokenType.ARRAY_OPEN) { format.append(enter(++depth)); } if (token.type == TokenType.SPLIT) { format.append(enter(depth)); } } return format.toString(); }
privatestatic List<Token> parseTextToTokens(String text)throws Exception { List<Token> tokens = new ArrayList<>(); while (!text.isEmpty()) { Token token = null; for (TokenType type : TokenType.values()) { token = getFirstToken(text, type); if (token != null) { break; } } if (token == null) { thrownew Exception(); } text = text.substring(token.value.length()); if (token.type == TokenType.SPACE) { continue; } tokens.add(token); } return tokens; }