最近了解到使用json字符串存到数据库的一种存储方式,取出来的json字符串可以进行相应的节点操作

故借此机会练习下递归,完成对json节点操作对应的工具类。

介绍一下我使用的依赖

  1.      <!-- fastjson -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.49</version>
  6. </dependency>

主要使用JSONObject和JSONArray的API进行相关操作,这里附上这两个类的代码

  1. /*
  2. * Copyright 1999-2017 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.alibaba.fastjson;
  17. import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal;
  18. import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger;
  19. import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
  20. import static com.alibaba.fastjson.util.TypeUtils.castToByte;
  21. import static com.alibaba.fastjson.util.TypeUtils.castToBytes;
  22. import static com.alibaba.fastjson.util.TypeUtils.castToDate;
  23. import static com.alibaba.fastjson.util.TypeUtils.castToDouble;
  24. import static com.alibaba.fastjson.util.TypeUtils.castToFloat;
  25. import static com.alibaba.fastjson.util.TypeUtils.castToInt;
  26. import static com.alibaba.fastjson.util.TypeUtils.castToLong;
  27. import static com.alibaba.fastjson.util.TypeUtils.castToShort;
  28. import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate;
  29. import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp;
  30. import java.io.*;
  31. import java.lang.reflect.Field;
  32. import java.lang.reflect.InvocationHandler;
  33. import java.lang.reflect.Method;
  34. import java.lang.reflect.Type;
  35. import java.math.BigDecimal;
  36. import java.math.BigInteger;
  37. import java.util.Collection;
  38. import java.util.Date;
  39. import java.util.HashMap;
  40. import java.util.LinkedHashMap;
  41. import java.util.Map;
  42. import java.util.Set;
  43. import com.alibaba.fastjson.annotation.JSONField;
  44. import com.alibaba.fastjson.parser.ParserConfig;
  45. import com.alibaba.fastjson.util.TypeUtils;
  46. /**
  47. * @author wenshao[szujobs@hotmail.com]
  48. */
  49. public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler {
  50. private static final long serialVersionUID = 1L;
  51. private static final int DEFAULT_INITIAL_CAPACITY = 16;
  52. private final Map<String, Object> map;
  53. public JSONObject(){
  54. this(DEFAULT_INITIAL_CAPACITY, false);
  55. }
  56. public JSONObject(Map<String, Object> map){
  57. if (map == null) {
  58. throw new IllegalArgumentException("map is null.");
  59. }
  60. this.map = map;
  61. }
  62. public JSONObject(boolean ordered){
  63. this(DEFAULT_INITIAL_CAPACITY, ordered);
  64. }
  65. public JSONObject(int initialCapacity){
  66. this(initialCapacity, false);
  67. }
  68. public JSONObject(int initialCapacity, boolean ordered){
  69. if (ordered) {
  70. map = new LinkedHashMap<String, Object>(initialCapacity);
  71. } else {
  72. map = new HashMap<String, Object>(initialCapacity);
  73. }
  74. }
  75. public int size() {
  76. return map.size();
  77. }
  78. public boolean isEmpty() {
  79. return map.isEmpty();
  80. }
  81. public boolean containsKey(Object key) {
  82. return map.containsKey(key);
  83. }
  84. public boolean containsValue(Object value) {
  85. return map.containsValue(value);
  86. }
  87. public Object get(Object key) {
  88. Object val = map.get(key);
  89. if (val == null && key instanceof Number) {
  90. val = map.get(key.toString());
  91. }
  92. return val;
  93. }
  94. public JSONObject getJSONObject(String key) {
  95. Object value = map.get(key);
  96. if (value instanceof JSONObject) {
  97. return (JSONObject) value;
  98. }
  99. if (value instanceof String) {
  100. return JSON.parseObject((String) value);
  101. }
  102. return (JSONObject) toJSON(value);
  103. }
  104. public JSONArray getJSONArray(String key) {
  105. Object value = map.get(key);
  106. if (value instanceof JSONArray) {
  107. return (JSONArray) value;
  108. }
  109. if (value instanceof String) {
  110. return (JSONArray) JSON.parse((String) value);
  111. }
  112. return (JSONArray) toJSON(value);
  113. }
  114. public <T> T getObject(String key, Class<T> clazz) {
  115. Object obj = map.get(key);
  116. return TypeUtils.castToJavaBean(obj, clazz);
  117. }
  118. public <T> T getObject(String key, Type type) {
  119. Object obj = map.get(key);
  120. return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance());
  121. }
  122. public <T> T getObject(String key, TypeReference typeReference) {
  123. Object obj = map.get(key);
  124. if (typeReference == null) {
  125. return (T) obj;
  126. }
  127. return TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance());
  128. }
  129. public Boolean getBoolean(String key) {
  130. Object value = get(key);
  131. if (value == null) {
  132. return null;
  133. }
  134. return castToBoolean(value);
  135. }
  136. public byte[] getBytes(String key) {
  137. Object value = get(key);
  138. if (value == null) {
  139. return null;
  140. }
  141. return castToBytes(value);
  142. }
  143. public boolean getBooleanValue(String key) {
  144. Object value = get(key);
  145. Boolean booleanVal = castToBoolean(value);
  146. if (booleanVal == null) {
  147. return false;
  148. }
  149. return booleanVal.booleanValue();
  150. }
  151. public Byte getByte(String key) {
  152. Object value = get(key);
  153. return castToByte(value);
  154. }
  155. public byte getByteValue(String key) {
  156. Object value = get(key);
  157. Byte byteVal = castToByte(value);
  158. if (byteVal == null) {
  159. return 0;
  160. }
  161. return byteVal.byteValue();
  162. }
  163. public Short getShort(String key) {
  164. Object value = get(key);
  165. return castToShort(value);
  166. }
  167. public short getShortValue(String key) {
  168. Object value = get(key);
  169. Short shortVal = castToShort(value);
  170. if (shortVal == null) {
  171. return 0;
  172. }
  173. return shortVal.shortValue();
  174. }
  175. public Integer getInteger(String key) {
  176. Object value = get(key);
  177. return castToInt(value);
  178. }
  179. public int getIntValue(String key) {
  180. Object value = get(key);
  181. Integer intVal = castToInt(value);
  182. if (intVal == null) {
  183. return 0;
  184. }
  185. return intVal.intValue();
  186. }
  187. public Long getLong(String key) {
  188. Object value = get(key);
  189. return castToLong(value);
  190. }
  191. public long getLongValue(String key) {
  192. Object value = get(key);
  193. Long longVal = castToLong(value);
  194. if (longVal == null) {
  195. return 0L;
  196. }
  197. return longVal.longValue();
  198. }
  199. public Float getFloat(String key) {
  200. Object value = get(key);
  201. return castToFloat(value);
  202. }
  203. public float getFloatValue(String key) {
  204. Object value = get(key);
  205. Float floatValue = castToFloat(value);
  206. if (floatValue == null) {
  207. return 0F;
  208. }
  209. return floatValue.floatValue();
  210. }
  211. public Double getDouble(String key) {
  212. Object value = get(key);
  213. return castToDouble(value);
  214. }
  215. public double getDoubleValue(String key) {
  216. Object value = get(key);
  217. Double doubleValue = castToDouble(value);
  218. if (doubleValue == null) {
  219. return 0D;
  220. }
  221. return doubleValue.doubleValue();
  222. }
  223. public BigDecimal getBigDecimal(String key) {
  224. Object value = get(key);
  225. return castToBigDecimal(value);
  226. }
  227. public BigInteger getBigInteger(String key) {
  228. Object value = get(key);
  229. return castToBigInteger(value);
  230. }
  231. public String getString(String key) {
  232. Object value = get(key);
  233. if (value == null) {
  234. return null;
  235. }
  236. return value.toString();
  237. }
  238. public Date getDate(String key) {
  239. Object value = get(key);
  240. return castToDate(value);
  241. }
  242. public java.sql.Date getSqlDate(String key) {
  243. Object value = get(key);
  244. return castToSqlDate(value);
  245. }
  246. public java.sql.Timestamp getTimestamp(String key) {
  247. Object value = get(key);
  248. return castToTimestamp(value);
  249. }
  250. public Object put(String key, Object value) {
  251. return map.put(key, value);
  252. }
  253. public JSONObject fluentPut(String key, Object value) {
  254. map.put(key, value);
  255. return this;
  256. }
  257. public void putAll(Map<? extends String, ? extends Object> m) {
  258. map.putAll(m);
  259. }
  260. public JSONObject fluentPutAll(Map<? extends String, ? extends Object> m) {
  261. map.putAll(m);
  262. return this;
  263. }
  264. public void clear() {
  265. map.clear();
  266. }
  267. public JSONObject fluentClear() {
  268. map.clear();
  269. return this;
  270. }
  271. public Object remove(Object key) {
  272. return map.remove(key);
  273. }
  274. public JSONObject fluentRemove(Object key) {
  275. map.remove(key);
  276. return this;
  277. }
  278. public Set<String> keySet() {
  279. return map.keySet();
  280. }
  281. public Collection<Object> values() {
  282. return map.values();
  283. }
  284. public Set<Map.Entry<String, Object>> entrySet() {
  285. return map.entrySet();
  286. }
  287. @Override
  288. public Object clone() {
  289. return new JSONObject(map instanceof LinkedHashMap //
  290. ? new LinkedHashMap<String, Object>(map) //
  291. : new HashMap<String, Object>(map)
  292. );
  293. }
  294. public boolean equals(Object obj) {
  295. return this.map.equals(obj);
  296. }
  297. public int hashCode() {
  298. return this.map.hashCode();
  299. }
  300. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  301. Class<?>[] parameterTypes = method.getParameterTypes();
  302. if (parameterTypes.length == 1) {
  303. if (method.getName().equals("equals")) {
  304. return this.equals(args[0]);
  305. }
  306. Class<?> returnType = method.getReturnType();
  307. if (returnType != void.class) {
  308. throw new JSONException("illegal setter");
  309. }
  310. String name = null;
  311. JSONField annotation = method.getAnnotation(JSONField.class);
  312. if (annotation != null) {
  313. if (annotation.name().length() != 0) {
  314. name = annotation.name();
  315. }
  316. }
  317. if (name == null) {
  318. name = method.getName();
  319. if (!name.startsWith("set")) {
  320. throw new JSONException("illegal setter");
  321. }
  322. name = name.substring(3);
  323. if (name.length() == 0) {
  324. throw new JSONException("illegal setter");
  325. }
  326. name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
  327. }
  328. map.put(name, args[0]);
  329. return null;
  330. }
  331. if (parameterTypes.length == 0) {
  332. Class<?> returnType = method.getReturnType();
  333. if (returnType == void.class) {
  334. throw new JSONException("illegal getter");
  335. }
  336. String name = null;
  337. JSONField annotation = method.getAnnotation(JSONField.class);
  338. if (annotation != null) {
  339. if (annotation.name().length() != 0) {
  340. name = annotation.name();
  341. }
  342. }
  343. if (name == null) {
  344. name = method.getName();
  345. if (name.startsWith("get")) {
  346. name = name.substring(3);
  347. if (name.length() == 0) {
  348. throw new JSONException("illegal getter");
  349. }
  350. name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
  351. } else if (name.startsWith("is")) {
  352. name = name.substring(2);
  353. if (name.length() == 0) {
  354. throw new JSONException("illegal getter");
  355. }
  356. name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
  357. } else if (name.startsWith("hashCode")) {
  358. return this.hashCode();
  359. } else if (name.startsWith("toString")) {
  360. return this.toString();
  361. } else {
  362. throw new JSONException("illegal getter");
  363. }
  364. }
  365. Object value = map.get(name);
  366. return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
  367. }
  368. throw new UnsupportedOperationException(method.toGenericString());
  369. }
  370. public Map<String, Object> getInnerMap() {
  371. return this.map;
  372. }
  373. private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
  374. SecureObjectInputStream.ensureFields();
  375. if (SecureObjectInputStream.fields != null && !SecureObjectInputStream.fields_error) {
  376. ObjectInputStream secIn = new SecureObjectInputStream(in);
  377. secIn.defaultReadObject();
  378. return;
  379. }
  380. in.defaultReadObject();
  381. for (Entry entry : map.entrySet()) {
  382. final Object key = entry.getKey();
  383. if (key != null) {
  384. ParserConfig.global.checkAutoType(key.getClass().getName(), null);
  385. }
  386. final Object value = entry.getValue();
  387. if (value != null) {
  388. ParserConfig.global.checkAutoType(value.getClass().getName(), null);
  389. }
  390. }
  391. }
  392. static class SecureObjectInputStream extends ObjectInputStream {
  393. static Field[] fields;
  394. static volatile boolean fields_error;
  395. static void ensureFields() {
  396. if (fields == null && !fields_error) {
  397. try {
  398. final Field[] declaredFields = ObjectInputStream.class.getDeclaredFields();
  399. String[] fieldnames = new String[]{"bin", "passHandle", "handles", "curContext"};
  400. Field[] array = new Field[fieldnames.length];
  401. for (int i = 0; i < fieldnames.length; i++) {
  402. Field field = TypeUtils
  403. .getField(ObjectInputStream.class
  404. , fieldnames[i]
  405. , declaredFields
  406. );
  407. field.setAccessible(true);
  408. array[i] = field;
  409. }
  410. fields = array;
  411. } catch (Throwable error) {
  412. fields_error = true;
  413. }
  414. }
  415. }
  416. public SecureObjectInputStream(ObjectInputStream in) throws IOException {
  417. super(in);
  418. try {
  419. for (int i = 0; i < fields.length; i++) {
  420. final Field field = fields[i];
  421. final Object value = field.get(in);
  422. field.set(this, value);
  423. }
  424. } catch (IllegalAccessException e) {
  425. fields_error = true;
  426. }
  427. }
  428. protected Class<?> resolveClass(ObjectStreamClass desc)
  429. throws IOException, ClassNotFoundException {
  430. String name = desc.getName();
  431. ParserConfig.global.checkAutoType(name, null);
  432. return super.resolveClass(desc);
  433. }
  434. protected Class<?> resolveProxyClass(String[] interfaces)
  435. throws IOException, ClassNotFoundException {
  436. for (String interfacename : interfaces) {
  437. //检查是否处于黑名单
  438. ParserConfig.global.checkAutoType(interfacename, null);
  439. }
  440. return super.resolveProxyClass(interfaces);
  441. }
  442. //Hack:默认构造方法会调用这个方法,重写此方法使用反射还原部分关键属性
  443. protected void readStreamHeader() throws IOException, StreamCorruptedException {
  444. }
  445. }
  446. }

JSONObject

  1. /*
  2. * Copyright 1999-2017 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.alibaba.fastjson;
  17. import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal;
  18. import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger;
  19. import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
  20. import static com.alibaba.fastjson.util.TypeUtils.castToByte;
  21. import static com.alibaba.fastjson.util.TypeUtils.castToDate;
  22. import static com.alibaba.fastjson.util.TypeUtils.castToDouble;
  23. import static com.alibaba.fastjson.util.TypeUtils.castToFloat;
  24. import static com.alibaba.fastjson.util.TypeUtils.castToInt;
  25. import static com.alibaba.fastjson.util.TypeUtils.castToLong;
  26. import static com.alibaba.fastjson.util.TypeUtils.castToShort;
  27. import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate;
  28. import static com.alibaba.fastjson.util.TypeUtils.castToString;
  29. import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp;
  30. import java.io.IOException;
  31. import java.io.ObjectInputStream;
  32. import java.io.Serializable;
  33. import java.lang.reflect.Type;
  34. import java.math.BigDecimal;
  35. import java.math.BigInteger;
  36. import java.util.*;
  37. import com.alibaba.fastjson.parser.ParserConfig;
  38. import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
  39. import com.alibaba.fastjson.util.TypeUtils;
  40. /**
  41. * @author wenshao[szujobs@hotmail.com]
  42. */
  43. public class JSONArray extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable {
  44. private static final long serialVersionUID = 1L;
  45. private final List<Object> list;
  46. protected transient Object relatedArray;
  47. protected transient Type componentType;
  48. public JSONArray(){
  49. this.list = new ArrayList<Object>();
  50. }
  51. public JSONArray(List<Object> list){
  52. this.list = list;
  53. }
  54. public JSONArray(int initialCapacity){
  55. this.list = new ArrayList<Object>(initialCapacity);
  56. }
  57. /**
  58. * @since 1.1.16
  59. * @return
  60. */
  61. public Object getRelatedArray() {
  62. return relatedArray;
  63. }
  64. public void setRelatedArray(Object relatedArray) {
  65. this.relatedArray = relatedArray;
  66. }
  67. public Type getComponentType() {
  68. return componentType;
  69. }
  70. public void setComponentType(Type componentType) {
  71. this.componentType = componentType;
  72. }
  73. public int size() {
  74. return list.size();
  75. }
  76. public boolean isEmpty() {
  77. return list.isEmpty();
  78. }
  79. public boolean contains(Object o) {
  80. return list.contains(o);
  81. }
  82. public Iterator<Object> iterator() {
  83. return list.iterator();
  84. }
  85. public Object[] toArray() {
  86. return list.toArray();
  87. }
  88. public <T> T[] toArray(T[] a) {
  89. return list.toArray(a);
  90. }
  91. public boolean add(Object e) {
  92. return list.add(e);
  93. }
  94. public JSONArray fluentAdd(Object e) {
  95. list.add(e);
  96. return this;
  97. }
  98. public boolean remove(Object o) {
  99. return list.remove(o);
  100. }
  101. public JSONArray fluentRemove(Object o) {
  102. list.remove(o);
  103. return this;
  104. }
  105. public boolean containsAll(Collection<?> c) {
  106. return list.containsAll(c);
  107. }
  108. public boolean addAll(Collection<? extends Object> c) {
  109. return list.addAll(c);
  110. }
  111. public JSONArray fluentAddAll(Collection<? extends Object> c) {
  112. list.addAll(c);
  113. return this;
  114. }
  115. public boolean addAll(int index, Collection<? extends Object> c) {
  116. return list.addAll(index, c);
  117. }
  118. public JSONArray fluentAddAll(int index, Collection<? extends Object> c) {
  119. list.addAll(index, c);
  120. return this;
  121. }
  122. public boolean removeAll(Collection<?> c) {
  123. return list.removeAll(c);
  124. }
  125. public JSONArray fluentRemoveAll(Collection<?> c) {
  126. list.removeAll(c);
  127. return this;
  128. }
  129. public boolean retainAll(Collection<?> c) {
  130. return list.retainAll(c);
  131. }
  132. public JSONArray fluentRetainAll(Collection<?> c) {
  133. list.retainAll(c);
  134. return this;
  135. }
  136. public void clear() {
  137. list.clear();
  138. }
  139. public JSONArray fluentClear() {
  140. list.clear();
  141. return this;
  142. }
  143. public Object set(int index, Object element) {
  144. if (index == -1) {
  145. list.add(element);
  146. return null;
  147. }
  148. if (list.size() <= index) {
  149. for (int i = list.size(); i < index; ++i) {
  150. list.add(null);
  151. }
  152. list.add(element);
  153. return null;
  154. }
  155. return list.set(index, element);
  156. }
  157. public JSONArray fluentSet(int index, Object element) {
  158. set(index, element);
  159. return this;
  160. }
  161. public void add(int index, Object element) {
  162. list.add(index, element);
  163. }
  164. public JSONArray fluentAdd(int index, Object element) {
  165. list.add(index, element);
  166. return this;
  167. }
  168. public Object remove(int index) {
  169. return list.remove(index);
  170. }
  171. public JSONArray fluentRemove(int index) {
  172. list.remove(index);
  173. return this;
  174. }
  175. public int indexOf(Object o) {
  176. return list.indexOf(o);
  177. }
  178. public int lastIndexOf(Object o) {
  179. return list.lastIndexOf(o);
  180. }
  181. public ListIterator<Object> listIterator() {
  182. return list.listIterator();
  183. }
  184. public ListIterator<Object> listIterator(int index) {
  185. return list.listIterator(index);
  186. }
  187. public List<Object> subList(int fromIndex, int toIndex) {
  188. return list.subList(fromIndex, toIndex);
  189. }
  190. public Object get(int index) {
  191. return list.get(index);
  192. }
  193. public JSONObject getJSONObject(int index) {
  194. Object value = list.get(index);
  195. if (value instanceof JSONObject) {
  196. return (JSONObject) value;
  197. }
  198. return (JSONObject) toJSON(value);
  199. }
  200. public JSONArray getJSONArray(int index) {
  201. Object value = list.get(index);
  202. if (value instanceof JSONArray) {
  203. return (JSONArray) value;
  204. }
  205. return (JSONArray) toJSON(value);
  206. }
  207. public <T> T getObject(int index, Class<T> clazz) {
  208. Object obj = list.get(index);
  209. return TypeUtils.castToJavaBean(obj, clazz);
  210. }
  211. public <T> T getObject(int index, Type type) {
  212. Object obj = list.get(index);
  213. if (type instanceof Class) {
  214. return (T) TypeUtils.castToJavaBean(obj, (Class) type);
  215. } else {
  216. String json = JSON.toJSONString(obj);
  217. return (T) JSON.parseObject(json, type);
  218. }
  219. }
  220. public Boolean getBoolean(int index) {
  221. Object value = get(index);
  222. if (value == null) {
  223. return null;
  224. }
  225. return castToBoolean(value);
  226. }
  227. public boolean getBooleanValue(int index) {
  228. Object value = get(index);
  229. if (value == null) {
  230. return false;
  231. }
  232. return castToBoolean(value).booleanValue();
  233. }
  234. public Byte getByte(int index) {
  235. Object value = get(index);
  236. return castToByte(value);
  237. }
  238. public byte getByteValue(int index) {
  239. Object value = get(index);
  240. if (value == null) {
  241. return 0;
  242. }
  243. return castToByte(value).byteValue();
  244. }
  245. public Short getShort(int index) {
  246. Object value = get(index);
  247. return castToShort(value);
  248. }
  249. public short getShortValue(int index) {
  250. Object value = get(index);
  251. if (value == null) {
  252. return 0;
  253. }
  254. return castToShort(value).shortValue();
  255. }
  256. public Integer getInteger(int index) {
  257. Object value = get(index);
  258. return castToInt(value);
  259. }
  260. public int getIntValue(int index) {
  261. Object value = get(index);
  262. if (value == null) {
  263. return 0;
  264. }
  265. return castToInt(value).intValue();
  266. }
  267. public Long getLong(int index) {
  268. Object value = get(index);
  269. return castToLong(value);
  270. }
  271. public long getLongValue(int index) {
  272. Object value = get(index);
  273. if (value == null) {
  274. return 0L;
  275. }
  276. return castToLong(value).longValue();
  277. }
  278. public Float getFloat(int index) {
  279. Object value = get(index);
  280. return castToFloat(value);
  281. }
  282. public float getFloatValue(int index) {
  283. Object value = get(index);
  284. if (value == null) {
  285. return 0F;
  286. }
  287. return castToFloat(value).floatValue();
  288. }
  289. public Double getDouble(int index) {
  290. Object value = get(index);
  291. return castToDouble(value);
  292. }
  293. public double getDoubleValue(int index) {
  294. Object value = get(index);
  295. if (value == null) {
  296. return 0D;
  297. }
  298. return castToDouble(value);
  299. }
  300. public BigDecimal getBigDecimal(int index) {
  301. Object value = get(index);
  302. return castToBigDecimal(value);
  303. }
  304. public BigInteger getBigInteger(int index) {
  305. Object value = get(index);
  306. return castToBigInteger(value);
  307. }
  308. public String getString(int index) {
  309. Object value = get(index);
  310. return castToString(value);
  311. }
  312. public java.util.Date getDate(int index) {
  313. Object value = get(index);
  314. return castToDate(value);
  315. }
  316. public java.sql.Date getSqlDate(int index) {
  317. Object value = get(index);
  318. return castToSqlDate(value);
  319. }
  320. public java.sql.Timestamp getTimestamp(int index) {
  321. Object value = get(index);
  322. return castToTimestamp(value);
  323. }
  324. /**
  325. * @since 1.2.23
  326. */
  327. public <T> List<T> toJavaList(Class<T> clazz) {
  328. List<T> list = new ArrayList<T>(this.size());
  329. ParserConfig config = ParserConfig.getGlobalInstance();
  330. for (Object item : this) {
  331. T classItem = (T) TypeUtils.cast(item, clazz, config);
  332. list.add(classItem);
  333. }
  334. return list;
  335. }
  336. @Override
  337. public Object clone() {
  338. return new JSONArray(new ArrayList<Object>(list));
  339. }
  340. public boolean equals(Object obj) {
  341. return this.list.equals(obj);
  342. }
  343. public int hashCode() {
  344. return this.list.hashCode();
  345. }
  346. private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
  347. JSONObject.SecureObjectInputStream.ensureFields();
  348. if (JSONObject.SecureObjectInputStream.fields != null && !JSONObject.SecureObjectInputStream.fields_error) {
  349. ObjectInputStream secIn = new JSONObject.SecureObjectInputStream(in);
  350. secIn.defaultReadObject();
  351. return;
  352. }
  353. in.defaultReadObject();
  354. for (Object item : list) {
  355. if (item != null) {
  356. ParserConfig.global.checkAutoType(item.getClass().getName(), null);
  357. }
  358. }
  359. }
  360. }

JSONArray

一些数据转换的API

JSONArray.parseArray(“json树字符串”)———–可以返回JSONArray对象

jsonArray对象.toJSONString()————————可以转换为字符串便于存入数据库

 

首先我们需要有一个json树,这里可以自己编写,跟数据库操作的相关方法暂不涉及,这里直接使用相关API搭建,在main方法中

  1. public static void main(String[] args) {
  2. JSONArray details=new JSONArray();
  3. JSONObject tree1=new JSONObject();
  4. tree1.put("id",1);
  5. tree1.put("code", "taosir");
  6. tree1.put("name", "taosir");
  7. JSONObject tree2=new JSONObject();
  8. tree2.put("id",2);
  9. tree2.put("code", "moer");
  10. tree2.put("name", "moer");
  11. JSONArray array1=new JSONArray();
  12. array1.add(tree1);
  13. array1.add(tree2);
  14. JSONObject tree3=new JSONObject();
  15. tree3.put("id",3);
  16. tree3.put("code", "xixi");
  17. tree3.put("name", "xixi");
  18. tree3.put("children", array1);
  19. JSONObject tree4=new JSONObject();
  20. tree4.put("id",4);
  21. tree4.put("code", "jack");
  22. tree4.put("name", "jack");
  23. JSONArray array2=new JSONArray();
  24. array2.add(tree3);
  25. array2.add(tree4);
  26. JSONObject tree5=new JSONObject();
  27. tree5.put("id",5);
  28. tree5.put("code", "lay");
  29. tree5.put("name", "lay");
  30. tree5.put("children", array2);
  31. JSONObject tree6=new JSONObject();
  32. tree6.put("id",6);
  33. tree6.put("code", "haer");
  34. tree6.put("name", "haer");
  35. details.add(tree5);
  36. details.add(tree6);
  37. System.out.println(details);
  38. }

[{
    "id":5,
    "code":"lay",
    "name":"lay",
    "children":[{
        "id":3,
        "code":"xixi",
        "name":"xixi",
        "children":[{
            "code":"taosir",
            "name":"taosir",
            "id":1
        },{
            "code":"moer",
            "name":"moer",
            "id":2
        }]
    },{
        "id":4
        "code":"jack",
        "name":"jack"
    }]
},{
    "code":"haer",
    "name":"haer",
    "id":6
}]

生成的json树

点击上面可以查看生成的json树

OK,准备工作完毕,下面进行功能演示。

注意,每演示一个功能点,请注释掉其他的打印语句

 

首先是查询:

/**
     * 根据单一条件获取节点位置
     * @param body            查询目标的主体内容
     * @param key            筛选匹配条件条件对应--key
     * @param value            筛选匹配条件对应--value
     * @param result        缓存查询结果
     * @return
     */
    public static JSONObject getNode(JSONArray body,String key,Object value,JSONObject result) {
        for (int i = 0; i < body.size(); i++) {
            JSONObject jsonObject =body.getJSONObject(i);
            if (jsonObject.get(key).toString().equals(value.toString())) {
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    result.put(entry.getKey(), entry.getValue());
                }
            }else if(jsonObject.getJSONArray("children")!=null) {
                getNode(jsonObject.getJSONArray("children"), key, value,result);
            }
        }
        return result;
    }

在main方法调用演示,将前面的打印注释掉

//System.out.println(details);
System.out.println(getNode(details, "id", 4,new JSONObject()));

 

查询写出来,基本思路对了,其他的操作都类似,简单得多

下面是添加

/**
     * 
     * @param body            需要添加的目标树主体
     * @param key            筛选匹配条件对应的key
     * @param value            筛选匹配条件的值
     * @param index            需要插入的下标位置索引
     * @param node            插入的整体节点
     */
    public static void addNode(JSONArray body,String key,Object value,int index,JSONObject node) {
        for (int i = 0; i < body.size(); i++) {
            if("id".equals(key)&&"0".equals(value.toString())) {
                body.add(index, node);
                break;
            }
            JSONObject jsonObject =body.getJSONObject(i);
            if (jsonObject.get(key).toString().equals(value.toString())) {
                jsonObject.getJSONArray("children").add(index, node);
            }else if(jsonObject.getJSONArray("children")!=null) {
                addNode(jsonObject.getJSONArray("children"), key, value,index,node);
            }
        }
    }
System.out.println(getNode(details, "id",6 ,new JSONObject()));
JSONObject tree7=new JSONObject();
tree7.put("id",7);
tree7.put("code", "bom");
tree7.put("name", "bom");
addNode(details, "id", 6, 0, tree7);
System.out.println(getNode(details, "id",6 ,new JSONObject()));

可以看到,当节点位置没有子节点时,默认追加,这个时候需要传0,没有考虑越界,可以弄自定义异常处理

System.out.println(getNode(details, "id",6 ,new JSONObject()));
JSONObject tree8=new JSONObject();
tree8.put("id",8);
tree8.put("code", "naonao");
tree8.put("name", "naonao");
addNode(details, "id", 6, 0, tree8);
System.out.println(getNode(details, "id",6 ,new JSONObject()));

这种是已经有节点的情况,可以看到为直接插入索引位置

 

下面是删除,不保留孩子节点:

    /**
     * 根据单一条件删除节点
     * @param body        需要删除的目标主体
     * @param key        筛选匹配条件对应的key
     * @param value        筛选匹配条件对应的value
     */
    public static void delNode(JSONArray body,String key,Object value) {
        for (int i = 0; i < body.size(); i++) {
            JSONObject jsonObject =body.getJSONObject(i);
            if (jsonObject.get(key).toString().equals(value.toString())) {
                body.remove(i);
                break;
            }else if(jsonObject.getJSONArray("children")!=null) {
                delNode(jsonObject.getJSONArray("children"), key, value);
            }
        }
    }
System.out.println(getNode(details, "id",6 ,new JSONObject()));
delNode(details, "id", 8);
System.out.println(getNode(details, "id",6 ,new JSONObject()));

可以看到刚才加入的节点(id=8)已经被成功删除

 

下面是修改,可以选择是否保留孩子节点

/**
     * 根据单一条件修改节点
     * @param body        需要修改的目标主体
     * @param key        筛选匹配条件对应的key
     * @param value        筛选匹配条件对应的value
     * @param result    修改节点信息
     * @param isKeep    是否保留孩子节点
     */
    public static void updateNode(JSONArray body,String key,Object value,JSONObject result,boolean isKeep) {
        for (int i = 0; i < body.size(); i++) {
            JSONObject jsonObject =body.getJSONObject(i);
            if (jsonObject.get(key).toString().equals(value.toString())) {
                if(isKeep)
                    result.put("children", jsonObject.getJSONArray("children"));
                body.set(i, result);
                break;
            }else if(jsonObject.getJSONArray("children")!=null) {
                updateNode(jsonObject.getJSONArray("children"), key, value,result,isKeep);
            }
        }
    }

当需要保留孩子节点时:

System.out.println(getNode(details, "id",6 ,new JSONObject()));
JSONObject tree9=new JSONObject();
tree9.put("id",6);
tree9.put("code", "bom");
tree9.put("name", "bom");
updateNode(details, "id", 6, tree9, true);
System.out.println(getNode(details, "id",6 ,new JSONObject()));

当不需要保留孩子节点时:

System.out.println(getNode(details, "id",6 ,new JSONObject()));
JSONObject tree9=new JSONObject();
tree9.put("id",6);
tree9.put("code", "bom");
tree9.put("name", "bom");
updateNode(details, "id", 6, tree9, false);
System.out.println(getNode(details, "id",6 ,new JSONObject()));

 

以上,为简单的增删查改,根据业务不同会有不同的更改。

虽然业务要求匹配ID即可,不过这里以单一条件的匹配,能正常实现也能应对需要匹配其他字段的情况

每个人的实现方式不同,这里仅是我个人的思路与实现,仅供参考。

新人一枚,如有疑问或建议,欢迎提出!

 

版权声明:本文为it-taosir原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/it-taosir/p/9860829.html