Building a Java library which implements JSON conversion between JSON strings and Java beans. The source code is available in here .
Object => JSONElement Firstly, check the type of the object to see if it can be directly converted to JSONPrimitive, JSONList, JSONMap. Otherwise, treat it as a record and use reflection to extract the field name and value and convert it to JSONMap.
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 59 60 61 62 63 64 65 66 public static JSONElement analyze (Object o) { if (null == o) { return JSONElement.theVoid(); } if (o instanceof JSONElement) { return (JSONElement) o; } Class<?> cls = o.getClass(); if (o instanceof String) { return JSONElement.newPrimitive(o); } else if (o instanceof Number) { return JSONElement.newPrimitive(o); } else if (TypeUtil.isPrimitive(o)) { return JSONElement.newPrimitive(o); } else if (cls.isEnum()) { return JSONElement.newPrimitive(((Enum) o).ordinal()); } else if (cls.isArray()) { JSONElement list = JSONElement.newList(); for (int i = 0 ; i < Array.getLength(o); i++) { list.offer(analyze(Array.get(o, i))); } return list; } else if (o instanceof Iterable) { JSONElement list = JSONElement.newList(); for (Object oo : (Iterable) o) { list.offer(analyze(oo)); } return list; } else if (o instanceof Enumeration) { JSONElement list = JSONElement.newList(); Enumeration es = (Enumeration) o; while (es.hasMoreElements()) { list.offer(analyze(es.nextElement())); } return list; } else if (o instanceof Map) { JSONElement map = JSONElement.newMap(); for (Object e : ((Map) o).entrySet()) { map.offer(StringUtil.toString(((Map.Entry) e).getKey()), analyze(((Map.Entry) e).getValue())); } return map; } else if (o instanceof Dictionary) { JSONElement map = JSONElement.newMap(); Enumeration keys = ((Dictionary) o).keys(); while (keys.hasMoreElements()) { Object k = keys.nextElement(); map.offer(StringUtil.toString(k), analyze(((Dictionary) o).get(k))); } return map; } else { JSONElement map = JSONElement.newMap(); for (Field f : ObjectUtil.getFields(cls)) { try { map.offer(f.getName(), analyze(f.get(o))); } catch (IllegalAccessException ignored) { } } return map; } }
JSONElement => Object The basic idea is to get the field name of the target type and then take the value into recursion.
The source code is too long to show it here. Check ObjectAnalyzer instead.