Skip to content

Instantly share code, notes, and snippets.

@FantomJAC
Created July 16, 2013 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FantomJAC/6007794 to your computer and use it in GitHub Desktop.
Save FantomJAC/6007794 to your computer and use it in GitHub Desktop.
適当JSON
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
public class Parser {
public static final char START_OBJECT = '{';
public static final char KEY = ':';
public static final char VALUE = ',';
public static final char END_OBJECT = '}';
private CharBuffer buffer;
private char current;
public Parser(CharBuffer buffer) {
this.buffer = buffer;
}
public Parser(String json) {
this.buffer = CharBuffer.wrap(json);
}
private Object pull() {
StringBuilder sb = new StringBuilder();
while (true) {
current = buffer.get();
if (current == START_OBJECT || current == KEY || current == VALUE || current == END_OBJECT) {
break;
}
sb.append(current);
}
String s = sb.toString();
if (s.isEmpty()) {
return null;
}
if (s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
return s.substring(1, s.length() - 1);
} else {
return Integer.parseInt(s);
}
}
public Object parse() {
HashMap map = new HashMap();
String key = "";
PARSE:
do {
Object val = pull();
switch (current) {
case KEY:
key = val.toString();
break;
case START_OBJECT:
val = parse();
case END_OBJECT:
case VALUE:
map.put(key, val);
if (current == END_OBJECT) {
break PARSE;
}
break;
}
} while (buffer.remaining() > 0);
return map;
}
public static void main(String[] args) {
Parser parser = new Parser("{\"apple\":123,\"orange\":456,\"hoge\":{\"xyz\":\"test\"}}");
Map map = (Map) parser.parse();
System.out.print(map);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment