FastJsonUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package com.persagy.util;
  2. import java.lang.reflect.Array;
  3. import java.lang.reflect.Constructor;
  4. import java.lang.reflect.Method;
  5. import java.math.BigDecimal;
  6. import java.math.BigInteger;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.Iterator;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Set;
  15. import com.alibaba.fastjson.JSONArray;
  16. import com.alibaba.fastjson.JSONObject;
  17. public class FastJsonUtil {
  18. public static Set<Object> ValueArray2ValueSet(JSONArray valueArray) {
  19. Set<Object> valueSet = new HashSet<Object>();
  20. for (int index_va = 0; index_va < valueArray.size(); index_va++) {
  21. Object valueItem = valueArray.get(index_va);
  22. valueSet.add(valueItem);
  23. }
  24. return valueSet;
  25. }
  26. public static JSONArray ValueSet2ValueArray(Set<Object> valueSet) {
  27. JSONArray valueArray = new JSONArray();
  28. Iterator<Object> valueIter = valueSet.iterator();
  29. while (valueIter.hasNext()) {
  30. Object valueItem = valueIter.next();
  31. valueArray.add(valueItem);
  32. }
  33. return valueArray;
  34. }
  35. public static Set<Object> ValueSet_or(List<Set<Object>> valueSetList) {
  36. Set<Object> result = new HashSet<Object>();
  37. for (int i = 0; i < valueSetList.size(); i++) {
  38. Set<Object> valueSet = valueSetList.get(i);
  39. result.addAll(valueSet);
  40. }
  41. return result;
  42. }
  43. public static Set<Object> ValueSet_and(List<Set<Object>> valueSetList) {
  44. Set<Object> result = new HashSet<Object>();
  45. Set<Object> first = valueSetList.get(0);
  46. Iterator<Object> valueIter = first.iterator();
  47. while (valueIter.hasNext()) {
  48. Object valueItem = valueIter.next();
  49. boolean all_in = true;
  50. for (int i = 1; i < valueSetList.size(); i++) {
  51. Set<Object> valueSet = valueSetList.get(i);
  52. if (!valueSet.contains(valueItem)) {
  53. all_in = false;
  54. break;
  55. }
  56. }
  57. if (all_in) {
  58. result.add(valueItem);
  59. }
  60. }
  61. return result;
  62. }
  63. public static Set<Object> ValueSet_sub(Set<Object> valueSet1, Set<Object> valueSet2) {
  64. Set<Object> result = new HashSet<Object>();
  65. Iterator<Object> valueIter = valueSet1.iterator();
  66. while (valueIter.hasNext()) {
  67. Object valueItem = valueIter.next();
  68. if (!valueSet2.contains(valueItem)) {
  69. result.add(valueItem);
  70. }
  71. }
  72. return result;
  73. }
  74. public static String toFormatString(Object value) {
  75. return toStringInner(value, true);
  76. }
  77. public static String toString(Object value) {
  78. return toStringInner(value, false);
  79. }
  80. private static String toStringInner(Object value, boolean has_enter) {
  81. if (value == null)
  82. return "null";
  83. if (value instanceof String) {
  84. StringBuffer sb = new StringBuffer();
  85. escape((String) value, sb);
  86. return "\"" + sb.toString() + "\"";
  87. }
  88. if (value instanceof Double) {
  89. if (((Double) value).isInfinite() || ((Double) value).isNaN())
  90. return "null";
  91. else
  92. return value.toString();
  93. }
  94. if (value instanceof Float) {
  95. if (((Float) value).isInfinite() || ((Float) value).isNaN())
  96. return "null";
  97. else
  98. return value.toString();
  99. }
  100. if (value instanceof Number)
  101. return value.toString();
  102. if (value instanceof Boolean)
  103. return value.toString();
  104. if (value instanceof JSONObject) {
  105. JSONObject valueJSON = (JSONObject) value;
  106. StringBuffer sb = new StringBuffer();
  107. boolean first = true;
  108. Iterator<String> iter = valueJSON.keySet().iterator();
  109. sb.append('{');
  110. while (iter.hasNext()) {
  111. String key = iter.next();
  112. if (first)
  113. first = false;
  114. else
  115. sb.append(',');
  116. if (has_enter) {
  117. sb.append("\r\n\t");
  118. }
  119. sb.append('\"');
  120. escape(key, sb);
  121. sb.append('\"').append(':');
  122. String valueString = toStringInner(valueJSON.get(key), has_enter);
  123. sb.append(valueString.replaceAll("\r\n", "\r\n\t"));
  124. }
  125. if (has_enter) {
  126. sb.append("\r\n");
  127. }
  128. sb.append('}');
  129. return sb.toString();
  130. }
  131. if (value instanceof JSONArray) {
  132. JSONArray valueJSON = (JSONArray) value;
  133. boolean first = true;
  134. StringBuffer sb = new StringBuffer();
  135. sb.append('[');
  136. for (int i = 0; i < valueJSON.size(); i++) {
  137. if (first)
  138. first = false;
  139. else
  140. sb.append(',');
  141. if (has_enter) {
  142. sb.append("\r\n\t");
  143. }
  144. Object valueInner = valueJSON.get(i);
  145. if (valueInner == null) {
  146. sb.append("null");
  147. continue;
  148. }
  149. String valueString = toStringInner(valueInner, has_enter);
  150. sb.append(valueString.replaceAll("\r\n", "\r\n\t"));
  151. }
  152. if (has_enter) {
  153. sb.append("\r\n");
  154. }
  155. sb.append(']');
  156. return sb.toString();
  157. }
  158. return value.toString();
  159. }
  160. public static void escape(String s, StringBuffer sb) {
  161. for (int i = 0; i < s.length(); i++) {
  162. char ch = s.charAt(i);
  163. switch (ch) {
  164. case '"':
  165. sb.append("\\\"");
  166. break;
  167. case '\\':
  168. sb.append("\\\\");
  169. break;
  170. case '\b':
  171. sb.append("\\b");
  172. break;
  173. case '\f':
  174. sb.append("\\f");
  175. break;
  176. case '\n':
  177. sb.append("\\n");
  178. break;
  179. case '\r':
  180. sb.append("\\r");
  181. break;
  182. case '\t':
  183. sb.append("\\t");
  184. break;
  185. case '/':
  186. sb.append("\\/");
  187. break;
  188. default:
  189. // Reference: http://www.unicode.org/versions/Unicode5.1.0/
  190. if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) {
  191. String ss = Integer.toHexString(ch);
  192. sb.append("\\u");
  193. for (int k = 0; k < 4 - ss.length(); k++) {
  194. sb.append('0');
  195. }
  196. sb.append(ss.toUpperCase());
  197. } else {
  198. sb.append(ch);
  199. }
  200. }
  201. } // for
  202. }
  203. public static Long getLong(JSONObject json, String name) throws Exception {
  204. if (json.containsKey(name)) {
  205. Object item = json.get(name);
  206. if (item instanceof Integer) {
  207. return ((Integer) item).longValue();
  208. } else if (item instanceof Long) {
  209. return ((Long) item).longValue();
  210. } else if (item instanceof BigInteger) {
  211. return ((BigInteger) item).longValue();
  212. } else {
  213. throw new Exception("FastJsonUtil: " + "JSON property " + name + " cant Cast to Long:" + FastJsonUtil.toFormatString(json));
  214. }
  215. } else {
  216. return null;
  217. }
  218. }
  219. public static Long getDouble(JSONObject json, String name) throws Exception {
  220. if (json.containsKey(name)) {
  221. Object item = json.get(name);
  222. if (item instanceof Integer) {
  223. return ((Integer) item).longValue();
  224. } else if (item instanceof Long) {
  225. return ((Long) item).longValue();
  226. } else if (item instanceof BigInteger) {
  227. return ((BigInteger) item).longValue();
  228. } else if (item instanceof Float) {
  229. return ((Float) item).longValue();
  230. } else if (item instanceof Double) {
  231. return ((Double) item).longValue();
  232. } else if (item instanceof BigDecimal) {
  233. return ((BigDecimal) item).longValue();
  234. } else {
  235. throw new Exception("FastJsonUtil: " + "JSON property " + name + " cant Cast to Double:" + FastJsonUtil.toFormatString(json));
  236. }
  237. } else {
  238. return null;
  239. }
  240. }
  241. public static void Set_JSON(Object entity, JSONObject json) throws Exception {
  242. Class<?> targetClass = entity.getClass();
  243. Method[] targetMethodArray = targetClass.getMethods();
  244. for (int i = 0; i < targetMethodArray.length; i++) {
  245. Method method = targetMethodArray[i];
  246. int modifiers = method.getModifiers();
  247. String methodName = method.getName();
  248. if (modifiers == 1 && methodName.startsWith("get")) {
  249. Class<?>[] parameterTypes = method.getParameterTypes();
  250. if (parameterTypes.length == 0) {
  251. String fieldName = methodName.substring(3);
  252. fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
  253. if (json.containsKey(fieldName)) {
  254. json.remove(fieldName);
  255. }
  256. Object value = method.invoke(entity, new Object[] {});
  257. if (value != null) {
  258. String valueClassName = value.getClass().getName();
  259. Object put_value = null;
  260. if (valueClassName.equals("java.lang.String")) {
  261. put_value = value;
  262. } else if (valueClassName.equals("java.util.Date")) {
  263. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  264. put_value = sdf.format((Date) value);
  265. } else if (valueClassName.equals("java.lang.Long") || valueClassName.equals("long")) {
  266. put_value = value;
  267. } else if (valueClassName.equals("java.lang.Double") || valueClassName.equals("double")) {
  268. put_value = value;
  269. } else if (valueClassName.equals("java.lang.Boolean") || valueClassName.equals("boolean")) {
  270. put_value = value;
  271. } else {
  272. put_value = To_JSON(value);
  273. }
  274. json.put(fieldName, put_value);
  275. }
  276. }
  277. }
  278. }
  279. }
  280. public static void Set_JavaObject(JSONObject json, Object entity) throws Exception {
  281. Class<?> targetClass = entity.getClass();
  282. if (json == null) {
  283. return;
  284. }
  285. Method[] targetMethodArray = targetClass.getMethods();
  286. for (int i = 0; i < targetMethodArray.length; i++) {
  287. Method method = targetMethodArray[i];
  288. int modifiers = method.getModifiers();
  289. String methodName = method.getName();
  290. if (modifiers == 1 && methodName.startsWith("set")) {
  291. Class<?>[] parameterTypes = method.getParameterTypes();
  292. if (parameterTypes.length == 1) {
  293. String fieldName = methodName.substring(3);
  294. fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
  295. Class<?> paramClass = parameterTypes[0];
  296. if (json.containsKey(fieldName)) {
  297. Object sourceFieldValue = json.get(fieldName);
  298. Object targetFieldValue = To_JavaObject(sourceFieldValue, paramClass);
  299. method.invoke(entity, new Object[] { targetFieldValue });
  300. }
  301. }
  302. }
  303. }
  304. }
  305. public static Object To_JSON(Object source) throws Exception {
  306. Class<?> sourceClass = source.getClass();
  307. if (sourceClass.isArray()) {
  308. JSONArray result = new JSONArray();
  309. int array_length = Array.getLength(source);
  310. for (int i = 0; i < array_length; i++) {
  311. Object item = Array.get(source, i);
  312. result.add(To_JSON(item));
  313. }
  314. return result;
  315. } else {
  316. JSONObject result = new JSONObject();
  317. Method[] meethodArray = sourceClass.getMethods();
  318. for (int i = 0; i < meethodArray.length; i++) {
  319. Method method = meethodArray[i];
  320. int modifiers = method.getModifiers();
  321. String methodName = method.getName();
  322. if (modifiers == 1 && methodName.startsWith("get")) {
  323. Class<?>[] parameterTypes = method.getParameterTypes();
  324. if (parameterTypes.length == 0) {
  325. String fieldName = methodName.substring(3);
  326. fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
  327. Object value = method.invoke(source, new Object[] {});
  328. Object put_value;
  329. if (value == null) {
  330. put_value = null;
  331. } else {
  332. String valueClassName = value.getClass().getName();
  333. if (valueClassName.equals("java.lang.String")) {
  334. put_value = value;
  335. } else if (valueClassName.equals("java.util.Date")) {
  336. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  337. put_value = sdf.format(value);
  338. } else if (valueClassName.equals("java.lang.Long") || valueClassName.equals("long")) {
  339. put_value = value;
  340. } else if (valueClassName.equals("java.lang.Double") || valueClassName.equals("double")) {
  341. put_value = value;
  342. } else if (valueClassName.equals("java.lang.Boolean") || valueClassName.equals("boolean")) {
  343. put_value = value;
  344. } else {
  345. put_value = To_JSON(value);
  346. }
  347. }
  348. result.put(fieldName, put_value);
  349. }
  350. }
  351. }
  352. return result;
  353. }
  354. }
  355. public static Object To_JavaObject(Object json, Class<?> entityClass) throws Exception {
  356. if (json == null) {
  357. return null;
  358. }
  359. String targetClassName = entityClass.getName();
  360. if (json instanceof JSONArray && entityClass.isArray()) {
  361. JSONArray sourceEntity = (JSONArray) json;
  362. int sourceLength = sourceEntity.size();
  363. Class<?> targetComponentType = entityClass.getComponentType();
  364. Object targetObjectArray = Array.newInstance(targetComponentType, sourceLength);
  365. for (int i = 0; i < sourceLength; i++) {
  366. Object sourceObject = sourceEntity.get(i);
  367. Object targetObject = To_JavaObject(sourceObject, targetComponentType);
  368. Array.set(targetObjectArray, i, targetObject);
  369. }
  370. return targetObjectArray;
  371. } else if (json instanceof JSONObject) {
  372. JSONObject sourceEntity = (JSONObject) json;
  373. Constructor<?> constructorMethod = entityClass.getConstructor(new Class<?>[] {});
  374. Object targetObject = constructorMethod.newInstance(new Object[] {});
  375. Method[] methodArray = entityClass.getMethods();
  376. for (int i = 0; i < methodArray.length; i++) {
  377. Method method = methodArray[i];
  378. int modifiers = method.getModifiers();
  379. String methodName = method.getName();
  380. if (modifiers == 1 && methodName.startsWith("set")) {
  381. Class<?>[] parameterTypes = method.getParameterTypes();
  382. if (parameterTypes.length == 1) {
  383. String fieldName = methodName.substring(3);
  384. fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
  385. Class<?> paramClass = parameterTypes[0];
  386. if (sourceEntity.containsKey(fieldName)) {
  387. Object sourceFieldValue = sourceEntity.get(fieldName);
  388. Object targetFieldValue = To_JavaObject(sourceFieldValue, paramClass);
  389. method.invoke(targetObject, new Object[] { targetFieldValue });
  390. }
  391. }
  392. }
  393. }
  394. return targetObject;
  395. } else if (json instanceof String && targetClassName.equals("java.lang.String")) {
  396. return (String) json;
  397. } else if (json instanceof String && targetClassName.equals("java.util.Date")) {
  398. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  399. return sdf.parse((String) json);
  400. } else if (targetClassName.equals("java.lang.Long") || targetClassName.equals("long")) {
  401. if (json instanceof String) {
  402. Long value = Long.parseLong((String) json);
  403. return value;
  404. } else if (json instanceof Integer) {
  405. return ((Integer) json).longValue();
  406. } else if (json instanceof Long) {
  407. return ((Long) json).longValue();
  408. } else if (json instanceof BigInteger) {
  409. return ((BigInteger) json).longValue();
  410. } else {
  411. return null;
  412. }
  413. } else if (targetClassName.equals("java.lang.Double") || targetClassName.equals("double")) {
  414. if (json instanceof String) {
  415. Double value = Double.parseDouble((String) json);
  416. return value;
  417. } else if (json instanceof Integer) {
  418. return ((Integer) json).doubleValue();
  419. } else if (json instanceof Long) {
  420. return ((Long) json).doubleValue();
  421. } else if (json instanceof BigInteger) {
  422. return ((BigInteger) json).doubleValue();
  423. } else if (json instanceof Float) {
  424. return ((Float) json).doubleValue();
  425. } else if (json instanceof Double) {
  426. return ((Double) json).doubleValue();
  427. } else if (json instanceof BigDecimal) {
  428. return ((BigDecimal) json).doubleValue();
  429. } else {
  430. return null;
  431. }
  432. } else if (targetClassName.equals("java.lang.Boolean") || targetClassName.equals("boolean")) {
  433. if (json instanceof String) {
  434. Boolean value = ((String) json).equalsIgnoreCase("true") ? true : false;
  435. return value;
  436. } else if (json instanceof Boolean) {
  437. Boolean value = (Boolean) json;
  438. return value;
  439. } else {
  440. return null;
  441. }
  442. } else {
  443. return null;
  444. }
  445. }
  446. public static void Normalize(Object source) {
  447. if (source instanceof JSONObject) {
  448. JSONObject sourceJSON = (JSONObject) source;
  449. Map<String, Object> newMap = new HashMap<String, Object>();
  450. Iterator<String> keyIter = sourceJSON.keySet().iterator();
  451. while (keyIter.hasNext()) {
  452. String key = keyIter.next();
  453. Object value = sourceJSON.get(key);
  454. if (value == null) {
  455. continue;
  456. }
  457. if (value instanceof Integer) {
  458. newMap.put(key, ((Integer) value).longValue());
  459. } else if (value instanceof Long) {
  460. } else if (value instanceof BigInteger) {
  461. newMap.put(key, ((BigInteger) value).longValue());
  462. } else if (value instanceof Float) {
  463. newMap.put(key, ((Float) value).doubleValue());
  464. } else if (value instanceof Double) {
  465. } else if (value instanceof BigDecimal) {
  466. newMap.put(key, ((BigDecimal) value).doubleValue());
  467. } else if (value instanceof JSONObject || value instanceof JSONArray) {
  468. Normalize(value);
  469. }
  470. }
  471. Iterator<String> iter2 = newMap.keySet().iterator();
  472. while (iter2.hasNext()) {
  473. String key = iter2.next();
  474. Object value = newMap.get(key);
  475. sourceJSON.remove(key);
  476. sourceJSON.put(key, value);
  477. }
  478. } else if (source instanceof JSONArray) {
  479. JSONArray sourceJSON = (JSONArray) source;
  480. for (int i = 0; i < sourceJSON.size(); i++) {
  481. Object sourceItem = sourceJSON.get(i);
  482. if (sourceItem != null && (sourceItem instanceof JSONObject || sourceItem instanceof JSONArray)) {
  483. Normalize(sourceItem);
  484. }
  485. }
  486. }
  487. }
  488. public static Object Clone_JSON(Object source) {
  489. if (source instanceof JSONObject) {
  490. JSONObject result = new JSONObject();
  491. JSONObject sourceJSON = (JSONObject) source;
  492. Iterator<String> keyIter = sourceJSON.keySet().iterator();
  493. while (keyIter.hasNext()) {
  494. String key = keyIter.next();
  495. Object value = sourceJSON.get(key);
  496. result.put(key, Clone_JSON(value));
  497. }
  498. return result;
  499. } else if (source instanceof JSONArray) {
  500. JSONArray result = new JSONArray();
  501. JSONArray sourceJSON = (JSONArray) source;
  502. for (int i = 0; i < sourceJSON.size(); i++) {
  503. result.add(Clone_JSON(sourceJSON.get(i)));
  504. }
  505. return result;
  506. } else if (source instanceof String) {
  507. return source;
  508. } else if (source instanceof Double) {
  509. return source;
  510. } else if (source instanceof Long) {
  511. return source;
  512. } else if (source instanceof Boolean) {
  513. return source;
  514. }
  515. return null;
  516. }
  517. }