Building a Java library which implements JSON conversion between JSON strings and Java beans. The source code is available in here .
String => JSONElement Briefly, the basic idea is creating sub-elements during the traversal of json string. So traversing the json string, handling the keywords, and expecting the time complexity to be O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 for (char c : json.toCharArray()) { switch (c) { case '"' : case '\'' : break ; case '{' : break ; case '[' : break ; case ':' : break ; case ',' : break ; case '}' : break ; case ']' : break ; default : break ; } }
See StringAnalyzer for more details.
JSONElement => String Much easier than string => JSONElement . Recursively read sub-elements and append its value to a StringBuilder
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 public static String analyze (JSONElement element) { StringBuilder sb = new StringBuilder (); switch (element.getType()) { case LIST: sb.append('[' ); Iterator<JSONElement.Entry> iterator = element.iterator(); while (iterator.hasNext()) { sb.append(analyze(iterator.next().getElement())); if (iterator.hasNext()) { sb.append(',' ); } } sb.append(']' ); break ; case MAP: sb.append('{' ); Iterator<JSONElement.Entry> iterator1 = element.iterator(); while (iterator1.hasNext()) { JSONElement.Entry e = iterator1.next(); sb.append('"' ); sb.append(StringUtil.escape(StringUtil.toString(e.getKey()))); sb.append('"' ); sb.append(':' ); sb.append(analyze(e.getElement())); if (iterator1.hasNext()) { sb.append(',' ); } } sb.append('}' ); break ; case PRIMITIVE: Object v = element.asValue(); if (v instanceof String) { sb.append('"' ); sb.append(StringUtil.escape((String) v)); sb.append('"' ); } else { sb.append(StringUtil.toString(v)); } break ; case VOID: sb.append(StringUtil.NULL); break ; default : break ; } return sb.toString(); }