PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/JSON.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 648 lines | 472 code | 150 blank | 26 comment | 71 complexity | a8c3f8f3ea3bae0c86dad1456c767229 MD5 | raw file
  1. /*
  2. * Copyright 1999-2101 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 java.io.IOException;
  18. import java.lang.reflect.Array;
  19. import java.lang.reflect.Type;
  20. import java.nio.ByteBuffer;
  21. import java.nio.CharBuffer;
  22. import java.nio.charset.CharsetDecoder;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collection;
  26. import java.util.List;
  27. import java.util.Map;
  28. import com.alibaba.fastjson.parser.DefaultJSONParser;
  29. import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask;
  30. import com.alibaba.fastjson.parser.Feature;
  31. import com.alibaba.fastjson.parser.JSONLexer;
  32. import com.alibaba.fastjson.parser.JSONToken;
  33. import com.alibaba.fastjson.parser.ParserConfig;
  34. import com.alibaba.fastjson.parser.deserializer.FieldDeserializer;
  35. import com.alibaba.fastjson.serializer.JSONSerializer;
  36. import com.alibaba.fastjson.serializer.NameFilter;
  37. import com.alibaba.fastjson.serializer.PropertyPreFilter;
  38. import com.alibaba.fastjson.serializer.PropertyFilter;
  39. import com.alibaba.fastjson.serializer.SerializeConfig;
  40. import com.alibaba.fastjson.serializer.SerializeFilter;
  41. import com.alibaba.fastjson.serializer.SerializeWriter;
  42. import com.alibaba.fastjson.serializer.SerializerFeature;
  43. import com.alibaba.fastjson.serializer.ValueFilter;
  44. import com.alibaba.fastjson.util.FieldInfo;
  45. import com.alibaba.fastjson.util.IOUtils;
  46. import com.alibaba.fastjson.util.ThreadLocalCache;
  47. import com.alibaba.fastjson.util.TypeUtils;
  48. /**
  49. * @author wenshao<szujobs@hotmail.com>
  50. */
  51. public abstract class JSON implements JSONStreamAware, JSONAware {
  52. public static int DEFAULT_PARSER_FEATURE;
  53. static {
  54. int features = 0;
  55. features |= Feature.AutoCloseSource.getMask();
  56. features |= Feature.InternFieldNames.getMask();
  57. features |= Feature.UseBigDecimal.getMask();
  58. features |= Feature.AllowUnQuotedFieldNames.getMask();
  59. features |= Feature.AllowSingleQuotes.getMask();
  60. features |= Feature.AllowArbitraryCommas.getMask();
  61. features |= Feature.SortFeidFastMatch.getMask();
  62. features |= Feature.IgnoreNotMatch.getMask();
  63. DEFAULT_PARSER_FEATURE = features;
  64. }
  65. public static String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
  66. public static int DEFAULT_GENERATE_FEATURE;
  67. static {
  68. int features = 0;
  69. features |= com.alibaba.fastjson.serializer.SerializerFeature.QuoteFieldNames.getMask();
  70. features |= com.alibaba.fastjson.serializer.SerializerFeature.SkipTransientField.getMask();
  71. features |= com.alibaba.fastjson.serializer.SerializerFeature.WriteEnumUsingToString.getMask();
  72. features |= com.alibaba.fastjson.serializer.SerializerFeature.SortField.getMask();
  73. // features |= com.alibaba.fastjson.serializer.SerializerFeature.WriteTabAsSpecial.getMask();
  74. // features |= com.alibaba.fastjson.serializer.SerializerFeature.WriteSlashAsSpecial.getMask();
  75. DEFAULT_GENERATE_FEATURE = features;
  76. }
  77. public static final Object parse(String text) {
  78. return parse(text, DEFAULT_PARSER_FEATURE);
  79. }
  80. public static final Object parse(String text, int features) {
  81. if (text == null) {
  82. return null;
  83. }
  84. DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance(), features);
  85. Object value = parser.parse();
  86. handleResovleTask(parser, value);
  87. parser.close();
  88. return value;
  89. }
  90. public static final Object parse(byte[] input, Feature... features) {
  91. return parse(input, 0, input.length, ThreadLocalCache.getUTF8Decoder(), features);
  92. }
  93. public static final Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Feature... features) {
  94. if (input == null || input.length == 0) {
  95. return null;
  96. }
  97. int featureValues = DEFAULT_PARSER_FEATURE;
  98. for (Feature featrue : features) {
  99. featureValues = Feature.config(featureValues, featrue, true);
  100. }
  101. return parse(input, off, len, charsetDecoder, featureValues);
  102. }
  103. public static final Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) {
  104. charsetDecoder.reset();
  105. int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
  106. char[] chars = ThreadLocalCache.getChars(scaleLength);
  107. ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
  108. CharBuffer charBuf = CharBuffer.wrap(chars);
  109. IOUtils.decode(charsetDecoder, byteBuf, charBuf);
  110. int position = charBuf.position();
  111. DefaultJSONParser parser = new DefaultJSONParser(chars, position, ParserConfig.getGlobalInstance(), features);
  112. Object value = parser.parse();
  113. handleResovleTask(parser, value);
  114. parser.close();
  115. return value;
  116. }
  117. public static final Object parse(String text, Feature... features) {
  118. int featureValues = DEFAULT_PARSER_FEATURE;
  119. for (Feature featrue : features) {
  120. featureValues = Feature.config(featureValues, featrue, true);
  121. }
  122. return parse(text, featureValues);
  123. }
  124. public static final JSONObject parseObject(String text, Feature... features) {
  125. return (JSONObject) parse(text, features);
  126. }
  127. public static final JSONObject parseObject(String text) {
  128. Object obj = parse(text);
  129. if (obj instanceof JSONObject) {
  130. return (JSONObject) obj;
  131. }
  132. return (JSONObject) JSON.toJSON(obj);
  133. }
  134. @SuppressWarnings("unchecked")
  135. public static final <T> T parseObject(String text, TypeReference<T> type, Feature... features) {
  136. return (T) parseObject(text, type.getType(), ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features);
  137. }
  138. @SuppressWarnings("unchecked")
  139. public static final <T> T parseObject(String text, Class<T> clazz, Feature... features) {
  140. return (T) parseObject(text, (Type) clazz, ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features);
  141. }
  142. @SuppressWarnings("unchecked")
  143. public static final <T> T parseObject(String input, Type clazz, Feature... features) {
  144. return (T) parseObject(input, clazz, ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features);
  145. }
  146. @SuppressWarnings("unchecked")
  147. public static final <T> T parseObject(String input, Type clazz, int featureValues, Feature... features) {
  148. if (input == null) {
  149. return null;
  150. }
  151. for (Feature featrue : features) {
  152. featureValues = Feature.config(featureValues, featrue, true);
  153. }
  154. DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues);
  155. T value = (T) parser.parseObject(clazz);
  156. handleResovleTask(parser, value);
  157. parser.close();
  158. return (T) value;
  159. }
  160. @SuppressWarnings("unchecked")
  161. public static final <T> T parseObject(String input, Type clazz, ParserConfig config, int featureValues,
  162. Feature... features) {
  163. if (input == null) {
  164. return null;
  165. }
  166. for (Feature featrue : features) {
  167. featureValues = Feature.config(featureValues, featrue, true);
  168. }
  169. DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);
  170. T value = (T) parser.parseObject(clazz);
  171. handleResovleTask(parser, value);
  172. parser.close();
  173. return (T) value;
  174. }
  175. public static <T> int handleResovleTask(DefaultJSONParser parser, T value) {
  176. if (parser.isEnabled(Feature.DisableCircularReferenceDetect)) {
  177. return 0;
  178. }
  179. int size = parser.getResolveTaskList().size();
  180. for (int i = 0; i < size; ++i) {
  181. ResolveTask task = parser.getResolveTaskList().get(i);
  182. FieldDeserializer fieldDeser = task.getFieldDeserializer();
  183. Object object = null;
  184. if (task.getOwnerContext() != null) {
  185. object = task.getOwnerContext().getObject();
  186. }
  187. String ref = task.getReferenceValue();
  188. Object refValue;
  189. if (ref.startsWith("$")) {
  190. refValue = parser.getObject(ref);
  191. } else {
  192. refValue = task.getContext().getObject();
  193. }
  194. fieldDeser.setValue(object, refValue);
  195. }
  196. return size;
  197. }
  198. @SuppressWarnings("unchecked")
  199. public static final <T> T parseObject(byte[] input, Type clazz, Feature... features) {
  200. return (T) parseObject(input, 0, input.length, ThreadLocalCache.getUTF8Decoder(), clazz, features);
  201. }
  202. @SuppressWarnings("unchecked")
  203. public static final <T> T parseObject(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Type clazz,
  204. Feature... features) {
  205. charsetDecoder.reset();
  206. int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
  207. char[] chars = ThreadLocalCache.getChars(scaleLength);
  208. ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
  209. CharBuffer charByte = CharBuffer.wrap(chars);
  210. IOUtils.decode(charsetDecoder, byteBuf, charByte);
  211. int position = charByte.position();
  212. return (T) parseObject(chars, position, clazz, features);
  213. }
  214. @SuppressWarnings("unchecked")
  215. public static final <T> T parseObject(char[] input, int length, Type clazz, Feature... features) {
  216. if (input == null || input.length == 0) {
  217. return null;
  218. }
  219. int featureValues = DEFAULT_PARSER_FEATURE;
  220. for (Feature featrue : features) {
  221. featureValues = Feature.config(featureValues, featrue, true);
  222. }
  223. DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues);
  224. T value = (T) parser.parseObject(clazz);
  225. handleResovleTask(parser, value);
  226. parser.close();
  227. return (T) value;
  228. }
  229. public static final <T> T parseObject(String text, Class<T> clazz) {
  230. return parseObject(text, clazz, new Feature[0]);
  231. }
  232. public static final JSONArray parseArray(String text) {
  233. if (text == null) {
  234. return null;
  235. }
  236. DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
  237. JSONArray array;
  238. JSONLexer lexer = parser.getLexer();
  239. if (lexer.token() == JSONToken.NULL) {
  240. lexer.nextToken();
  241. array = null;
  242. } else if (lexer.token() == JSONToken.EOF) {
  243. array = null;
  244. } else {
  245. array = new JSONArray();
  246. parser.parseArray(array);
  247. handleResovleTask(parser, array);
  248. }
  249. parser.close();
  250. return array;
  251. }
  252. public static final <T> List<T> parseArray(String text, Class<T> clazz) {
  253. if (text == null) {
  254. return null;
  255. }
  256. List<T> list;
  257. DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
  258. JSONLexer lexer = parser.getLexer();
  259. if (lexer.token() == JSONToken.NULL) {
  260. lexer.nextToken();
  261. list = null;
  262. } else {
  263. list = new ArrayList<T>();
  264. parser.parseArray(clazz, list);
  265. handleResovleTask(parser, list);
  266. }
  267. parser.close();
  268. return list;
  269. }
  270. public static final List<Object> parseArray(String text, Type[] types) {
  271. if (text == null) {
  272. return null;
  273. }
  274. List<Object> list;
  275. DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
  276. Object[] objectArray = parser.parseArray(types);
  277. if (objectArray == null) {
  278. list = null;
  279. } else {
  280. list = Arrays.asList(objectArray);
  281. }
  282. handleResovleTask(parser, list);
  283. parser.close();
  284. return list;
  285. }
  286. // ======================
  287. public static final String toJSONString(Object object) {
  288. return toJSONString(object, new SerializerFeature[0]);
  289. }
  290. public static final String toJSONString(Object object, SerializerFeature... features) {
  291. SerializeWriter out = new SerializeWriter();
  292. try {
  293. JSONSerializer serializer = new JSONSerializer(out);
  294. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  295. serializer.config(feature, true);
  296. }
  297. serializer.write(object);
  298. return out.toString();
  299. } finally {
  300. out.close();
  301. }
  302. }
  303. /**
  304. * @since 1.1.14
  305. */
  306. public static final String toJSONStringWithDateFormat(Object object, String dateFormat,
  307. SerializerFeature... features) {
  308. SerializeWriter out = new SerializeWriter();
  309. try {
  310. JSONSerializer serializer = new JSONSerializer(out);
  311. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  312. serializer.config(feature, true);
  313. }
  314. serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
  315. if (dateFormat != null) {
  316. serializer.setDateFormat(dateFormat);
  317. }
  318. serializer.write(object);
  319. return out.toString();
  320. } finally {
  321. out.close();
  322. }
  323. }
  324. public static final String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) {
  325. SerializeWriter out = new SerializeWriter();
  326. try {
  327. JSONSerializer serializer = new JSONSerializer(out);
  328. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  329. serializer.config(feature, true);
  330. }
  331. serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
  332. if (filter != null) {
  333. if (filter instanceof PropertyPreFilter) {
  334. serializer.getPropertyPreFilters().add((PropertyPreFilter) filter);
  335. }
  336. if (filter instanceof NameFilter) {
  337. serializer.getNameFilters().add((NameFilter) filter);
  338. }
  339. if (filter instanceof ValueFilter) {
  340. serializer.getValueFilters().add((ValueFilter) filter);
  341. }
  342. if (filter instanceof PropertyFilter) {
  343. serializer.getPropertyFilters().add((PropertyFilter) filter);
  344. }
  345. }
  346. serializer.write(object);
  347. return out.toString();
  348. } finally {
  349. out.close();
  350. }
  351. }
  352. public static final byte[] toJSONBytes(Object object, SerializerFeature... features) {
  353. SerializeWriter out = new SerializeWriter();
  354. try {
  355. JSONSerializer serializer = new JSONSerializer(out);
  356. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  357. serializer.config(feature, true);
  358. }
  359. serializer.write(object);
  360. return out.toBytes("UTF-8");
  361. } finally {
  362. out.close();
  363. }
  364. }
  365. public static final String toJSONString(Object object, SerializeConfig config, SerializerFeature... features) {
  366. SerializeWriter out = new SerializeWriter();
  367. try {
  368. JSONSerializer serializer = new JSONSerializer(out, config);
  369. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  370. serializer.config(feature, true);
  371. }
  372. serializer.write(object);
  373. return out.toString();
  374. } finally {
  375. out.close();
  376. }
  377. }
  378. public static final String toJSONStringZ(Object object, SerializeConfig mapping, SerializerFeature... features) {
  379. SerializeWriter out = new SerializeWriter(features);
  380. try {
  381. JSONSerializer serializer = new JSONSerializer(out, mapping);
  382. serializer.write(object);
  383. return out.toString();
  384. } finally {
  385. out.close();
  386. }
  387. }
  388. public static final byte[] toJSONBytes(Object object, SerializeConfig config, SerializerFeature... features) {
  389. SerializeWriter out = new SerializeWriter();
  390. try {
  391. JSONSerializer serializer = new JSONSerializer(out, config);
  392. for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
  393. serializer.config(feature, true);
  394. }
  395. serializer.write(object);
  396. return out.toBytes("UTF-8");
  397. } finally {
  398. out.close();
  399. }
  400. }
  401. public static final String toJSONString(Object object, boolean prettyFormat) {
  402. if (!prettyFormat) {
  403. return toJSONString(object);
  404. }
  405. return toJSONString(object, SerializerFeature.PrettyFormat);
  406. }
  407. // ======================================
  408. @Override
  409. public String toString() {
  410. return toJSONString();
  411. }
  412. public String toJSONString() {
  413. SerializeWriter out = new SerializeWriter();
  414. try {
  415. new JSONSerializer(out).write(this);
  416. return out.toString();
  417. } finally {
  418. out.close();
  419. }
  420. }
  421. public void writeJSONString(Appendable appendable) {
  422. SerializeWriter out = new SerializeWriter();
  423. try {
  424. new JSONSerializer(out).write(this);
  425. appendable.append(out.toString());
  426. } catch (IOException e) {
  427. throw new JSONException(e.getMessage(), e);
  428. } finally {
  429. out.close();
  430. }
  431. }
  432. // ///////
  433. public static final Object toJSON(Object javaObject) {
  434. return toJSON(javaObject, ParserConfig.getGlobalInstance());
  435. }
  436. @SuppressWarnings("unchecked")
  437. public static final Object toJSON(Object javaObject, ParserConfig mapping) {
  438. if (javaObject == null) {
  439. return null;
  440. }
  441. if (javaObject instanceof JSON) {
  442. return (JSON) javaObject;
  443. }
  444. if (javaObject instanceof Map) {
  445. Map<Object, Object> map = (Map<Object, Object>) javaObject;
  446. JSONObject json = new JSONObject(map.size());
  447. for (Map.Entry<Object, Object> entry : map.entrySet()) {
  448. Object key = entry.getKey();
  449. String jsonKey = TypeUtils.castToString(key);
  450. Object jsonValue = toJSON(entry.getValue());
  451. json.put(jsonKey, jsonValue);
  452. }
  453. return json;
  454. }
  455. if (javaObject instanceof Collection) {
  456. Collection<Object> collection = (Collection<Object>) javaObject;
  457. JSONArray array = new JSONArray(collection.size());
  458. for (Object item : collection) {
  459. Object jsonValue = toJSON(item);
  460. array.add(jsonValue);
  461. }
  462. return array;
  463. }
  464. Class<?> clazz = javaObject.getClass();
  465. if (clazz.isEnum()) {
  466. return ((Enum<?>) javaObject).name();
  467. }
  468. if (clazz.isArray()) {
  469. int len = Array.getLength(javaObject);
  470. JSONArray array = new JSONArray(len);
  471. for (int i = 0; i < len; ++i) {
  472. Object item = Array.get(javaObject, i);
  473. Object jsonValue = toJSON(item);
  474. array.add(jsonValue);
  475. }
  476. return array;
  477. }
  478. if (mapping.isPrimitive(clazz)) {
  479. return javaObject;
  480. }
  481. try {
  482. List<FieldInfo> getters = TypeUtils.computeGetters(clazz, null);
  483. JSONObject json = new JSONObject(getters.size());
  484. for (FieldInfo field : getters) {
  485. Object value = field.get(javaObject);
  486. Object jsonValue = toJSON(value);
  487. json.put(field.getName(), jsonValue);
  488. }
  489. return json;
  490. } catch (Exception e) {
  491. throw new JSONException("toJSON error", e);
  492. }
  493. }
  494. public static final <T> T toJavaObject(JSON json, Class<T> clazz) {
  495. return TypeUtils.cast(json, clazz, ParserConfig.getGlobalInstance());
  496. }
  497. public final static String VERSION = "1.1.25";
  498. }