PageRenderTime 130ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 1163 lines | 968 code | 170 blank | 25 comment | 250 complexity | f5bf9a75a22eabf0d36fb56360f2d2d8 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.parser;
  17. import static com.alibaba.fastjson.parser.JSONScanner.EOI;
  18. import static com.alibaba.fastjson.parser.JSONToken.EOF;
  19. import static com.alibaba.fastjson.parser.JSONToken.ERROR;
  20. import static com.alibaba.fastjson.parser.JSONToken.FALSE;
  21. import static com.alibaba.fastjson.parser.JSONToken.LBRACE;
  22. import static com.alibaba.fastjson.parser.JSONToken.LBRACKET;
  23. import static com.alibaba.fastjson.parser.JSONToken.LITERAL_FLOAT;
  24. import static com.alibaba.fastjson.parser.JSONToken.LITERAL_INT;
  25. import static com.alibaba.fastjson.parser.JSONToken.LITERAL_STRING;
  26. import static com.alibaba.fastjson.parser.JSONToken.NEW;
  27. import static com.alibaba.fastjson.parser.JSONToken.NULL;
  28. import static com.alibaba.fastjson.parser.JSONToken.RBRACKET;
  29. import static com.alibaba.fastjson.parser.JSONToken.SET;
  30. import static com.alibaba.fastjson.parser.JSONToken.TREE_SET;
  31. import static com.alibaba.fastjson.parser.JSONToken.TRUE;
  32. import java.lang.reflect.ParameterizedType;
  33. import java.lang.reflect.Type;
  34. import java.lang.reflect.TypeVariable;
  35. import java.lang.reflect.WildcardType;
  36. import java.math.BigDecimal;
  37. import java.math.BigInteger;
  38. import java.text.DateFormat;
  39. import java.text.SimpleDateFormat;
  40. import java.util.ArrayList;
  41. import java.util.Collection;
  42. import java.util.Date;
  43. import java.util.HashSet;
  44. import java.util.List;
  45. import java.util.Map;
  46. import java.util.Set;
  47. import java.util.TreeSet;
  48. import com.alibaba.fastjson.JSON;
  49. import com.alibaba.fastjson.JSONArray;
  50. import com.alibaba.fastjson.JSONException;
  51. import com.alibaba.fastjson.JSONObject;
  52. import com.alibaba.fastjson.parser.deserializer.DefaultObjectDeserializer;
  53. import com.alibaba.fastjson.parser.deserializer.FieldDeserializer;
  54. import com.alibaba.fastjson.parser.deserializer.IntegerDeserializer;
  55. import com.alibaba.fastjson.parser.deserializer.ListResolveFieldDeserializer;
  56. import com.alibaba.fastjson.parser.deserializer.MapResolveFieldDeserializer;
  57. import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
  58. import com.alibaba.fastjson.parser.deserializer.StringDeserializer;
  59. import com.alibaba.fastjson.util.TypeUtils;
  60. /**
  61. * @author wenshao<szujobs@hotmail.com>
  62. */
  63. public class DefaultJSONParser extends AbstractJSONParser {
  64. protected final Object input;
  65. protected final SymbolTable symbolTable;
  66. protected ParserConfig config;
  67. private DefaultObjectDeserializer derializer = new DefaultObjectDeserializer();
  68. private final static Set<Class<?>> primitiveClasses = new HashSet<Class<?>>();
  69. private String dateFormatPattern = JSON.DEFFAULT_DATE_FORMAT;
  70. private DateFormat dateFormat;
  71. protected final JSONLexer lexer;
  72. protected ParseContext context;
  73. private ParseContext[] contextArray = new ParseContext[8];
  74. private int contextArrayIndex = 0;
  75. private final List<ResolveTask> resolveTaskList = new ArrayList<ResolveTask>();
  76. public final static int NONE = 0;
  77. public final static int NeedToResolve = 1;
  78. public final static int TypeNameRedirect = 2;
  79. private int resolveStatus = NONE;
  80. static {
  81. primitiveClasses.add(boolean.class);
  82. primitiveClasses.add(byte.class);
  83. primitiveClasses.add(short.class);
  84. primitiveClasses.add(int.class);
  85. primitiveClasses.add(long.class);
  86. primitiveClasses.add(float.class);
  87. primitiveClasses.add(double.class);
  88. primitiveClasses.add(Boolean.class);
  89. primitiveClasses.add(Byte.class);
  90. primitiveClasses.add(Short.class);
  91. primitiveClasses.add(Integer.class);
  92. primitiveClasses.add(Long.class);
  93. primitiveClasses.add(Float.class);
  94. primitiveClasses.add(Double.class);
  95. primitiveClasses.add(BigInteger.class);
  96. primitiveClasses.add(BigDecimal.class);
  97. primitiveClasses.add(String.class);
  98. }
  99. public String getDateFomartPattern() {
  100. return dateFormatPattern;
  101. }
  102. public DateFormat getDateFormat() {
  103. if (dateFormat == null) {
  104. dateFormat = new SimpleDateFormat(dateFormatPattern);
  105. }
  106. return dateFormat;
  107. }
  108. public void setDateFormat(String dateFormat) {
  109. this.dateFormatPattern = dateFormat;
  110. this.dateFormat = null;
  111. }
  112. public void setDateFomrat(DateFormat dateFormat) {
  113. this.dateFormat = dateFormat;
  114. }
  115. public DefaultJSONParser(String input){
  116. this(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE);
  117. }
  118. public DefaultJSONParser(final String input, final ParserConfig config){
  119. this(input, new JSONScanner(input, JSON.DEFAULT_PARSER_FEATURE), config);
  120. }
  121. public DefaultJSONParser(final String input, final ParserConfig config, int features){
  122. this(input, new JSONScanner(input, features), config);
  123. }
  124. public DefaultJSONParser(final char[] input, int length, final ParserConfig config, int features){
  125. this(input, new JSONScanner(input, length, features), config);
  126. }
  127. public DefaultJSONParser(final Object input, final JSONLexer lexer, final ParserConfig config){
  128. this.lexer = lexer;
  129. this.input = input;
  130. this.config = config;
  131. this.symbolTable = config.getSymbolTable();
  132. lexer.nextToken(JSONToken.LBRACE); // prime the pump
  133. }
  134. public SymbolTable getSymbolTable() {
  135. return symbolTable;
  136. }
  137. public String getInput() {
  138. if (input instanceof char[]) {
  139. return new String((char[]) input);
  140. }
  141. return input.toString();
  142. }
  143. @SuppressWarnings({ "unchecked", "rawtypes" })
  144. public final Object parseObject(final Map object, Object fieldName) {
  145. JSONScanner lexer = (JSONScanner) this.lexer;
  146. if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
  147. throw new JSONException("syntax error, expect {, actual " + lexer.tokenName());
  148. }
  149. ParseContext context = this.getContext();
  150. try {
  151. boolean setContextFlag = false;
  152. for (;;) {
  153. lexer.skipWhitespace();
  154. char ch = lexer.getCurrent();
  155. if (isEnabled(Feature.AllowArbitraryCommas)) {
  156. while (ch == ',') {
  157. lexer.incrementBufferPosition();
  158. lexer.skipWhitespace();
  159. ch = lexer.getCurrent();
  160. }
  161. }
  162. boolean isObjectKey = false;
  163. Object key;
  164. if (ch == '"') {
  165. key = lexer.scanSymbol(symbolTable, '"');
  166. lexer.skipWhitespace();
  167. ch = lexer.getCurrent();
  168. if (ch != ':') {
  169. throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key);
  170. }
  171. } else if (ch == '}') {
  172. lexer.incrementBufferPosition();
  173. lexer.resetStringPosition();
  174. lexer.nextToken();
  175. return object;
  176. } else if (ch == '\'') {
  177. if (!isEnabled(Feature.AllowSingleQuotes)) {
  178. throw new JSONException("syntax error");
  179. }
  180. key = lexer.scanSymbol(symbolTable, '\'');
  181. lexer.skipWhitespace();
  182. ch = lexer.getCurrent();
  183. if (ch != ':') {
  184. throw new JSONException("expect ':' at " + lexer.pos());
  185. }
  186. } else if (ch == EOI) {
  187. throw new JSONException("syntax error");
  188. } else if (ch == ',') {
  189. throw new JSONException("syntax error");
  190. } else if ((ch >= '0' && ch <= '9') || ch == '-') {
  191. lexer.resetStringPosition();
  192. lexer.scanNumber();
  193. if (lexer.token() == JSONToken.LITERAL_INT) {
  194. key = lexer.integerValue();
  195. } else {
  196. key = lexer.decimalValue(true);
  197. }
  198. ch = lexer.getCurrent();
  199. if (ch != ':') {
  200. throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key);
  201. }
  202. } else if (ch == '{' || ch == '[') {
  203. lexer.nextToken();
  204. key = parse();
  205. isObjectKey = true;
  206. } else {
  207. if (!isEnabled(Feature.AllowUnQuotedFieldNames)) {
  208. throw new JSONException("syntax error");
  209. }
  210. key = lexer.scanSymbolUnQuoted(symbolTable);
  211. lexer.skipWhitespace();
  212. ch = lexer.getCurrent();
  213. if (ch != ':') {
  214. throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch);
  215. }
  216. }
  217. if (!isObjectKey) {
  218. lexer.incrementBufferPosition();
  219. lexer.skipWhitespace();
  220. }
  221. ch = lexer.getCurrent();
  222. lexer.resetStringPosition();
  223. if (key == "@type") {
  224. String typeName = lexer.scanSymbol(symbolTable, '"');
  225. Class<?> clazz = TypeUtils.loadClass(typeName);
  226. if (clazz == null) {
  227. object.put("@type", typeName);
  228. continue;
  229. }
  230. lexer.nextToken(JSONToken.COMMA);
  231. if (lexer.token() == JSONToken.RBRACE) {
  232. lexer.nextToken(JSONToken.COMMA);
  233. try {
  234. return clazz.newInstance();
  235. } catch (Exception e) {
  236. throw new JSONException("create instance error", e);
  237. }
  238. }
  239. this.setResolveStatus(TypeNameRedirect);
  240. if (this.context != null && !(fieldName instanceof Integer)) {
  241. this.popContext();
  242. }
  243. ObjectDeserializer deserializer = config.getDeserializer(clazz);
  244. return deserializer.deserialze(this, clazz, fieldName);
  245. }
  246. if (key == "$ref") {
  247. lexer.nextToken(JSONToken.LITERAL_STRING);
  248. if (lexer.token() == JSONToken.LITERAL_STRING) {
  249. String ref = lexer.stringVal();
  250. lexer.nextToken(JSONToken.RBRACE);
  251. Object refValue = null;
  252. if ("@".equals(ref)) {
  253. if (this.getContext() != null) {
  254. refValue = this.getContext().getObject();
  255. }
  256. } else if ("..".equals(ref)) {
  257. ParseContext parentContext = context.getParentContext();
  258. if (parentContext.getObject() != null) {
  259. refValue = this.getContext().getObject();
  260. } else {
  261. addResolveTask(new ResolveTask(parentContext, ref));
  262. setResolveStatus(DefaultJSONParser.NeedToResolve);
  263. }
  264. } else if ("$".equals(ref)) {
  265. ParseContext rootContext = context;
  266. while (rootContext.getParentContext() != null) {
  267. rootContext = rootContext.getParentContext();
  268. }
  269. if (rootContext.getObject() != null) {
  270. refValue = rootContext.getObject();
  271. } else {
  272. addResolveTask(new ResolveTask(rootContext, ref));
  273. setResolveStatus(DefaultJSONParser.NeedToResolve);
  274. }
  275. } else {
  276. addResolveTask(new ResolveTask(context, ref));
  277. setResolveStatus(DefaultJSONParser.NeedToResolve);
  278. }
  279. if (lexer.token() != JSONToken.RBRACE) {
  280. throw new JSONException("syntax error");
  281. }
  282. lexer.nextToken(JSONToken.COMMA);
  283. return refValue;
  284. } else {
  285. throw new JSONException("illegal ref, " + JSONToken.name(lexer.token()));
  286. }
  287. }
  288. if (!setContextFlag) {
  289. setContext(object, fieldName);
  290. setContextFlag = true;
  291. }
  292. Object value;
  293. if (ch == '"') {
  294. lexer.scanString();
  295. String strValue = lexer.stringVal();
  296. value = strValue;
  297. if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
  298. JSONScanner iso8601Lexer = new JSONScanner(strValue);
  299. if (iso8601Lexer.scanISO8601DateIfMatch()) {
  300. value = iso8601Lexer.getCalendar().getTime();
  301. }
  302. }
  303. if (object.getClass() == JSONObject.class) {
  304. object.put(key.toString(), value);
  305. } else {
  306. object.put(key, value);
  307. }
  308. } else if (ch >= '0' && ch <= '9' || ch == '-') {
  309. lexer.scanNumber();
  310. if (lexer.token() == JSONToken.LITERAL_INT) {
  311. value = lexer.integerValue();
  312. } else {
  313. value = lexer.decimalValue();
  314. }
  315. object.put(key, value);
  316. } else if (ch == '[') { // 减少潜套,兼容android
  317. lexer.nextToken();
  318. JSONArray list = new JSONArray();
  319. this.parseArray(list, key);
  320. value = list;
  321. object.put(key, value);
  322. if (lexer.token() == JSONToken.RBRACE) {
  323. lexer.nextToken();
  324. return object;
  325. } else if (lexer.token() == JSONToken.COMMA) {
  326. continue;
  327. } else {
  328. throw new JSONException("syntax error");
  329. }
  330. } else if (ch == '{') { // 减少潜套,兼容android
  331. lexer.nextToken();
  332. Object obj = this.parseObject(new JSONObject(), key);
  333. checkMapResolve(object, key.toString());
  334. if (object.getClass() == JSONObject.class) {
  335. object.put(key.toString(), obj);
  336. } else {
  337. object.put(key, obj);
  338. }
  339. setContext(context, obj, key);
  340. if (lexer.token() == JSONToken.RBRACE) {
  341. lexer.nextToken();
  342. setContext(context);
  343. return object;
  344. } else if (lexer.token() == JSONToken.COMMA) {
  345. continue;
  346. } else {
  347. throw new JSONException("syntax error, " + lexer.tokenName());
  348. }
  349. } else {
  350. lexer.nextToken();
  351. value = parse();
  352. object.put(key, value);
  353. if (lexer.token() == JSONToken.RBRACE) {
  354. lexer.nextToken();
  355. return object;
  356. } else if (lexer.token() == JSONToken.COMMA) {
  357. continue;
  358. } else {
  359. throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key);
  360. }
  361. }
  362. lexer.skipWhitespace();
  363. ch = lexer.getCurrent();
  364. if (ch == ',') {
  365. lexer.incrementBufferPosition();
  366. continue;
  367. } else if (ch == '}') {
  368. lexer.incrementBufferPosition();
  369. lexer.resetStringPosition();
  370. lexer.nextToken();
  371. this.setContext(object, fieldName);
  372. return object;
  373. } else {
  374. throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key);
  375. }
  376. }
  377. } finally {
  378. this.setContext(context);
  379. }
  380. }
  381. public ParserConfig getConfig() {
  382. return config;
  383. }
  384. public void setConfig(ParserConfig config) {
  385. this.config = config;
  386. }
  387. // compatible
  388. @SuppressWarnings("unchecked")
  389. public <T> T parseObject(Class<T> clazz) {
  390. return (T) parseObject((Type) clazz);
  391. }
  392. @SuppressWarnings("unchecked")
  393. public <T> T parseObject(Type type) {
  394. if (lexer.token() == JSONToken.NULL) {
  395. lexer.nextToken();
  396. return null;
  397. }
  398. ObjectDeserializer derializer = config.getDeserializer(type);
  399. try {
  400. return (T) derializer.deserialze(this, type, null);
  401. } catch (JSONException e) {
  402. throw e;
  403. } catch (Throwable e) {
  404. throw new JSONException(e.getMessage(), e);
  405. }
  406. }
  407. public <T> List<T> parseArray(Class<T> clazz) {
  408. List<T> array = new ArrayList<T>();
  409. parseArray(clazz, array);
  410. return array;
  411. }
  412. public void parseArray(Class<?> clazz, @SuppressWarnings("rawtypes") Collection array) {
  413. parseArray((Type) clazz, array);
  414. }
  415. @SuppressWarnings("rawtypes")
  416. public void parseArray(Type type, Collection array) {
  417. parseArray(type, array, null);
  418. }
  419. @SuppressWarnings({ "unchecked", "rawtypes" })
  420. public void parseArray(Type type, Collection array, Object fieldName) {
  421. if (lexer.token() == JSONToken.SET || lexer.token() == JSONToken.TREE_SET) {
  422. lexer.nextToken();
  423. }
  424. if (lexer.token() != JSONToken.LBRACKET) {
  425. throw new JSONException("exepct '[', but " + JSONToken.name(lexer.token()));
  426. }
  427. ObjectDeserializer deserializer = null;
  428. if (int.class == type) {
  429. deserializer = IntegerDeserializer.instance;
  430. lexer.nextToken(JSONToken.LITERAL_INT);
  431. } else if (String.class == type) {
  432. deserializer = StringDeserializer.instance;
  433. lexer.nextToken(JSONToken.LITERAL_STRING);
  434. } else {
  435. deserializer = config.getDeserializer(type);
  436. lexer.nextToken(deserializer.getFastMatchToken());
  437. }
  438. ParseContext context = this.getContext();
  439. this.setContext(array, fieldName);
  440. try {
  441. for (int i = 0;; ++i) {
  442. if (isEnabled(Feature.AllowArbitraryCommas)) {
  443. while (lexer.token() == JSONToken.COMMA) {
  444. lexer.nextToken();
  445. continue;
  446. }
  447. }
  448. if (lexer.token() == JSONToken.RBRACKET) {
  449. break;
  450. }
  451. if (int.class == type) {
  452. Object val = IntegerDeserializer.deserialze(this);
  453. array.add(val);
  454. } else if (String.class == type) {
  455. String value;
  456. if (lexer.token() == JSONToken.LITERAL_STRING) {
  457. value = lexer.stringVal();
  458. lexer.nextToken(JSONToken.COMMA);
  459. } else {
  460. Object obj = this.parse();
  461. if (obj == null) {
  462. value = null;
  463. } else {
  464. value = obj.toString();
  465. }
  466. }
  467. array.add(value);
  468. } else {
  469. Object val;
  470. if (lexer.token() == JSONToken.NULL) {
  471. lexer.nextToken();
  472. val = null;
  473. } else {
  474. val = deserializer.deserialze(this, type, i);
  475. }
  476. array.add(val);
  477. checkListResolve(array);
  478. }
  479. if (lexer.token() == JSONToken.COMMA) {
  480. lexer.nextToken(deserializer.getFastMatchToken());
  481. continue;
  482. }
  483. }
  484. } finally {
  485. this.setContext(context);
  486. }
  487. lexer.nextToken(JSONToken.COMMA);
  488. }
  489. public Object[] parseArray(Type[] types) {
  490. if (lexer.token() == JSONToken.NULL) {
  491. lexer.nextToken(JSONToken.COMMA);
  492. return null;
  493. }
  494. if (lexer.token() != JSONToken.LBRACKET) {
  495. throw new JSONException("syntax error : " + lexer.tokenName());
  496. }
  497. Object[] list = new Object[types.length];
  498. if (types.length == 0) {
  499. lexer.nextToken(JSONToken.RBRACKET);
  500. if (lexer.token() != JSONToken.RBRACKET) {
  501. throw new JSONException("syntax error");
  502. }
  503. lexer.nextToken(JSONToken.COMMA);
  504. return new Object[0];
  505. }
  506. lexer.nextToken(JSONToken.LITERAL_INT);
  507. for (int i = 0; i < types.length; ++i) {
  508. Object value;
  509. if (lexer.token() == JSONToken.NULL) {
  510. value = null;
  511. lexer.nextToken(JSONToken.COMMA);
  512. } else {
  513. Type type = types[i];
  514. if (type == int.class || type == Integer.class) {
  515. if (lexer.token() == JSONToken.LITERAL_INT) {
  516. value = Integer.valueOf(lexer.intValue());
  517. lexer.nextToken(JSONToken.COMMA);
  518. } else {
  519. value = this.parse();
  520. value = TypeUtils.cast(value, type, config);
  521. }
  522. } else if (type == String.class) {
  523. if (lexer.token() == JSONToken.LITERAL_STRING) {
  524. value = lexer.stringVal();
  525. lexer.nextToken(JSONToken.COMMA);
  526. } else {
  527. value = this.parse();
  528. value = TypeUtils.cast(value, type, config);
  529. }
  530. } else {
  531. boolean isArray = false;
  532. Class<?> componentType = null;
  533. if (i == types.length - 1) {
  534. if (type instanceof Class) {
  535. Class<?> clazz = (Class<?>) type;
  536. isArray = clazz.isArray();
  537. componentType = clazz.getComponentType();
  538. }
  539. }
  540. // support varArgs
  541. if (isArray && lexer.token() != JSONToken.LBRACKET) {
  542. List<Object> varList = new ArrayList<Object>();
  543. ObjectDeserializer derializer = config.getDeserializer(componentType);
  544. int fastMatch = derializer.getFastMatchToken();
  545. if (lexer.token() != JSONToken.RBRACKET) {
  546. for (;;) {
  547. Object item = derializer.deserialze(this, type, null);
  548. varList.add(item);
  549. if (lexer.token() == JSONToken.COMMA) {
  550. lexer.nextToken(fastMatch);
  551. } else if (lexer.token() == JSONToken.RBRACKET) {
  552. break;
  553. } else {
  554. throw new JSONException("syntax error :" + JSONToken.name(lexer.token()));
  555. }
  556. }
  557. }
  558. value = TypeUtils.cast(varList, type, config);
  559. } else {
  560. ObjectDeserializer derializer = config.getDeserializer(type);
  561. value = derializer.deserialze(this, type, null);
  562. }
  563. }
  564. }
  565. list[i] = value;
  566. if (lexer.token() == JSONToken.RBRACKET) {
  567. break;
  568. }
  569. if (lexer.token() != JSONToken.COMMA) {
  570. throw new JSONException("syntax error :" + JSONToken.name(lexer.token()));
  571. }
  572. if (i == types.length - 1) {
  573. lexer.nextToken(JSONToken.RBRACKET);
  574. } else {
  575. lexer.nextToken(JSONToken.LITERAL_INT);
  576. }
  577. }
  578. if (lexer.token() != JSONToken.RBRACKET) {
  579. throw new JSONException("syntax error");
  580. }
  581. lexer.nextToken(JSONToken.COMMA);
  582. return list;
  583. }
  584. public void parseObject(Object object) {
  585. derializer.parseObject(this, object);
  586. }
  587. public Object parseArrayWithType(Type collectionType) {
  588. if (lexer.token() == JSONToken.NULL) {
  589. lexer.nextToken();
  590. return null;
  591. }
  592. Type[] actualTypes = ((ParameterizedType) collectionType).getActualTypeArguments();
  593. if (actualTypes.length != 1) {
  594. throw new JSONException("not support type " + collectionType);
  595. }
  596. Type actualTypeArgument = actualTypes[0];
  597. if (actualTypeArgument instanceof Class) {
  598. List<Object> array = new ArrayList<Object>();
  599. this.parseArray((Class<?>) actualTypeArgument, array);
  600. return array;
  601. }
  602. if (actualTypeArgument instanceof WildcardType) {
  603. WildcardType wildcardType = (WildcardType) actualTypeArgument;
  604. // assert wildcardType.getUpperBounds().length == 1;
  605. Type upperBoundType = wildcardType.getUpperBounds()[0];
  606. // assert upperBoundType instanceof Class;
  607. if (Object.class.equals(upperBoundType)) {
  608. if (wildcardType.getLowerBounds().length == 0) {
  609. // Collection<?>
  610. return parse();
  611. } else {
  612. throw new JSONException("not support type : " + collectionType);
  613. }
  614. }
  615. List<Object> array = new ArrayList<Object>();
  616. this.parseArray((Class<?>) upperBoundType, array);
  617. return array;
  618. // throw new JSONException("not support type : " +
  619. // collectionType);return parse();
  620. }
  621. if (actualTypeArgument instanceof TypeVariable) {
  622. TypeVariable<?> typeVariable = (TypeVariable<?>) actualTypeArgument;
  623. Type[] bounds = typeVariable.getBounds();
  624. if (bounds.length != 1) {
  625. throw new JSONException("not support : " + typeVariable);
  626. }
  627. Type boundType = bounds[0];
  628. if (boundType instanceof Class) {
  629. List<Object> array = new ArrayList<Object>();
  630. this.parseArray((Class<?>) boundType, array);
  631. return array;
  632. }
  633. }
  634. if (actualTypeArgument instanceof ParameterizedType) {
  635. ParameterizedType parameterizedType = (ParameterizedType) actualTypeArgument;
  636. List<Object> array = new ArrayList<Object>();
  637. this.parseArray(parameterizedType, array);
  638. return array;
  639. }
  640. throw new JSONException("TODO : " + collectionType);
  641. }
  642. public void acceptType(String typeName) {
  643. JSONScanner lexer = (JSONScanner) this.lexer;
  644. lexer.nextTokenWithColon();
  645. if (lexer.token() != JSONToken.LITERAL_STRING) {
  646. throw new JSONException("type not match error");
  647. }
  648. if (typeName.equals(lexer.stringVal())) {
  649. lexer.nextToken();
  650. if (lexer.token() == JSONToken.COMMA) {
  651. lexer.nextToken();
  652. }
  653. } else {
  654. throw new JSONException("type not match error");
  655. }
  656. }
  657. public int getResolveStatus() {
  658. return resolveStatus;
  659. }
  660. public void setResolveStatus(int resolveStatus) {
  661. this.resolveStatus = resolveStatus;
  662. }
  663. public Object getObject(String path) {
  664. for (int i = 0; i < contextArrayIndex; ++i) {
  665. if (path.equals(contextArray[i].getPath())) {
  666. return contextArray[i].getObject();
  667. }
  668. }
  669. return null;
  670. }
  671. @SuppressWarnings("rawtypes")
  672. public void checkListResolve(Collection array) {
  673. if (resolveStatus == NeedToResolve) {
  674. final int index = array.size() - 1;
  675. final List list = (List) array;
  676. ResolveTask task = getLastResolveTask();
  677. task.setFieldDeserializer(new ListResolveFieldDeserializer(this, list, index));
  678. task.setOwnerContext(context);
  679. setResolveStatus(DefaultJSONParser.NONE);
  680. }
  681. }
  682. @SuppressWarnings("rawtypes")
  683. public void checkMapResolve(Map object, String fieldName) {
  684. if (resolveStatus == NeedToResolve) {
  685. MapResolveFieldDeserializer fieldResolver = new MapResolveFieldDeserializer(object, fieldName);
  686. ResolveTask task = getLastResolveTask();
  687. task.setFieldDeserializer(fieldResolver);
  688. task.setOwnerContext(context);
  689. setResolveStatus(DefaultJSONParser.NONE);
  690. }
  691. }
  692. @SuppressWarnings("rawtypes")
  693. public Object parseObject(final Map object) {
  694. return parseObject(object, null);
  695. }
  696. public JSONObject parseObject() {
  697. JSONObject object = new JSONObject();
  698. parseObject(object);
  699. return object;
  700. }
  701. @SuppressWarnings("rawtypes")
  702. public final void parseArray(final Collection array) {
  703. parseArray(array, null);
  704. }
  705. @SuppressWarnings({ "unchecked", "rawtypes" })
  706. public final void parseArray(final Collection array, Object fieldName) {
  707. final JSONLexer lexer = getLexer();
  708. if (lexer.token() == JSONToken.SET || lexer.token() == JSONToken.TREE_SET) {
  709. lexer.nextToken();
  710. }
  711. if (lexer.token() != JSONToken.LBRACKET) {
  712. throw new JSONException("syntax error, expect [, actual " + JSONToken.name(lexer.token()));
  713. }
  714. lexer.nextToken(JSONToken.LITERAL_STRING);
  715. ParseContext context = this.getContext();
  716. this.setContext(array, fieldName);
  717. try {
  718. for (int i = 0;; ++i) {
  719. if (isEnabled(Feature.AllowArbitraryCommas)) {
  720. while (lexer.token() == JSONToken.COMMA) {
  721. lexer.nextToken();
  722. continue;
  723. }
  724. }
  725. Object value;
  726. switch (lexer.token()) {
  727. case LITERAL_INT:
  728. value = lexer.integerValue();
  729. lexer.nextToken(JSONToken.COMMA);
  730. break;
  731. case LITERAL_FLOAT:
  732. if (lexer.isEnabled(Feature.UseBigDecimal)) {
  733. value = lexer.decimalValue(true);
  734. } else {
  735. value = lexer.decimalValue(false);
  736. }
  737. lexer.nextToken(JSONToken.COMMA);
  738. break;
  739. case LITERAL_STRING:
  740. String stringLiteral = lexer.stringVal();
  741. lexer.nextToken(JSONToken.COMMA);
  742. if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
  743. JSONScanner iso8601Lexer = new JSONScanner(stringLiteral);
  744. if (iso8601Lexer.scanISO8601DateIfMatch()) {
  745. value = iso8601Lexer.getCalendar().getTime();
  746. } else {
  747. value = stringLiteral;
  748. }
  749. } else {
  750. value = stringLiteral;
  751. }
  752. break;
  753. case TRUE:
  754. value = Boolean.TRUE;
  755. lexer.nextToken(JSONToken.COMMA);
  756. break;
  757. case FALSE:
  758. value = Boolean.FALSE;
  759. lexer.nextToken(JSONToken.COMMA);
  760. break;
  761. case LBRACE:
  762. JSONObject object = new JSONObject();
  763. value = parseObject(object, i);
  764. break;
  765. case LBRACKET:
  766. Collection items = new JSONArray();
  767. parseArray(items, i);
  768. value = items;
  769. break;
  770. case NULL:
  771. value = null;
  772. lexer.nextToken(JSONToken.LITERAL_STRING);
  773. break;
  774. case RBRACKET:
  775. lexer.nextToken(JSONToken.COMMA);
  776. return;
  777. default:
  778. value = parse();
  779. break;
  780. }
  781. array.add(value);
  782. checkListResolve(array);
  783. if (lexer.token() == JSONToken.COMMA) {
  784. lexer.nextToken(JSONToken.LITERAL_STRING);
  785. continue;
  786. }
  787. }
  788. } finally {
  789. this.setContext(context);
  790. }
  791. }
  792. public ParseContext getContext() {
  793. return context;
  794. }
  795. public List<ResolveTask> getResolveTaskList() {
  796. return resolveTaskList;
  797. }
  798. public void addResolveTask(ResolveTask task) {
  799. resolveTaskList.add(task);
  800. }
  801. public ResolveTask getLastResolveTask() {
  802. return resolveTaskList.get(resolveTaskList.size() - 1);
  803. }
  804. public void setContext(ParseContext context) {
  805. if (isEnabled(Feature.DisableCircularReferenceDetect)) {
  806. return;
  807. }
  808. this.context = context;
  809. }
  810. public void popContext() {
  811. if (isEnabled(Feature.DisableCircularReferenceDetect)) {
  812. return;
  813. }
  814. this.context = this.context.getParentContext();
  815. contextArray[contextArrayIndex - 1] = null;
  816. contextArrayIndex--;
  817. }
  818. public ParseContext setContext(Object object, Object fieldName) {
  819. if (isEnabled(Feature.DisableCircularReferenceDetect)) {
  820. return null;
  821. }
  822. return setContext(this.context, object, fieldName);
  823. }
  824. public ParseContext setContext(ParseContext parent, Object object, Object fieldName) {
  825. if (isEnabled(Feature.DisableCircularReferenceDetect)) {
  826. return null;
  827. }
  828. this.context = new ParseContext(parent, object, fieldName);
  829. addContext(this.context);
  830. return this.context;
  831. }
  832. public int getContextLength() {
  833. return contextArrayIndex;
  834. }
  835. public void clearContext(ParseContext context, int start) {
  836. for (int i = start; i < contextArrayIndex; ++i) {
  837. contextArray[i] = null;
  838. }
  839. contextArrayIndex = start;
  840. this.context = context;
  841. }
  842. private void addContext(ParseContext context) {
  843. int i = contextArrayIndex++;
  844. if (i >= contextArray.length) {
  845. int newLen = (contextArray.length * 3) / 2;
  846. ParseContext[] newArray = new ParseContext[newLen];
  847. System.arraycopy(contextArray, 0, newArray, 0, contextArray.length);
  848. contextArray = newArray;
  849. }
  850. contextArray[i] = context;
  851. }
  852. public Object parse() {
  853. return parse(null);
  854. }
  855. public Object parse(Object fieldName) {
  856. final JSONLexer lexer = getLexer();
  857. switch (lexer.token()) {
  858. case SET:
  859. lexer.nextToken();
  860. HashSet<Object> set = new HashSet<Object>();
  861. parseArray(set, fieldName);
  862. return set;
  863. case TREE_SET:
  864. lexer.nextToken();
  865. TreeSet<Object> treeSet = new TreeSet<Object>();
  866. parseArray(treeSet, fieldName);
  867. return treeSet;
  868. case LBRACKET:
  869. JSONArray array = new JSONArray();
  870. parseArray(array, fieldName);
  871. return array;
  872. case LBRACE:
  873. JSONObject object = new JSONObject();
  874. return parseObject(object, fieldName);
  875. case LITERAL_INT:
  876. Number intValue = lexer.integerValue();
  877. lexer.nextToken();
  878. return intValue;
  879. case LITERAL_FLOAT:
  880. Object value = lexer.decimalValue(isEnabled(Feature.UseBigDecimal));
  881. lexer.nextToken();
  882. return value;
  883. case LITERAL_STRING:
  884. String stringLiteral = lexer.stringVal();
  885. lexer.nextToken(JSONToken.COMMA);
  886. if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
  887. JSONScanner iso8601Lexer = new JSONScanner(stringLiteral);
  888. if (iso8601Lexer.scanISO8601DateIfMatch()) {
  889. return iso8601Lexer.getCalendar().getTime();
  890. }
  891. }
  892. return stringLiteral;
  893. case NULL:
  894. lexer.nextToken();
  895. return null;
  896. case TRUE:
  897. lexer.nextToken();
  898. return Boolean.TRUE;
  899. case FALSE:
  900. lexer.nextToken();
  901. return Boolean.FALSE;
  902. case NEW:
  903. lexer.nextToken(JSONToken.IDENTIFIER);
  904. if (lexer.token() != JSONToken.IDENTIFIER) {
  905. throw new JSONException("syntax error");
  906. }
  907. lexer.nextToken(JSONToken.LPAREN);
  908. accept(JSONToken.LPAREN);
  909. long time = ((Number) lexer.integerValue()).longValue();
  910. accept(JSONToken.LITERAL_INT);
  911. accept(JSONToken.RPAREN);
  912. return new Date(time);
  913. case EOF:
  914. if (lexer.isBlankInput()) {
  915. return null;
  916. }
  917. throw new JSONException("unterminated json string, pos " + lexer.getBufferPosition());
  918. case ERROR:
  919. default:
  920. throw new JSONException("syntax error, pos " + lexer.getBufferPosition());
  921. }
  922. }
  923. public void config(Feature feature, boolean state) {
  924. getLexer().config(feature, state);
  925. }
  926. public boolean isEnabled(Feature feature) {
  927. return getLexer().isEnabled(feature);
  928. }
  929. public JSONLexer getLexer() {
  930. return lexer;
  931. }
  932. public final void accept(final int token) {
  933. final JSONLexer lexer = getLexer();
  934. if (lexer.token() == token) {
  935. lexer.nextToken();
  936. } else {
  937. throw new JSONException("syntax error, expect " + JSONToken.name(token) + ", actual "
  938. + JSONToken.name(lexer.token()));
  939. }
  940. }
  941. public void close() {
  942. final JSONLexer lexer = getLexer();
  943. try {
  944. if (isEnabled(Feature.AutoCloseSource)) {
  945. if (!lexer.isEOF()) {
  946. throw new JSONException("not close json text, token : " + JSONToken.name(lexer.token()));
  947. }
  948. }
  949. } finally {
  950. lexer.close();
  951. }
  952. }
  953. public static class ResolveTask {
  954. private final ParseContext context;
  955. private final String referenceValue;
  956. private FieldDeserializer fieldDeserializer;
  957. private ParseContext ownerContext;
  958. public ResolveTask(ParseContext context, String referenceValue){
  959. this.context = context;
  960. this.referenceValue = referenceValue;
  961. }
  962. public ParseContext getContext() {
  963. return context;
  964. }
  965. public String getReferenceValue() {
  966. return referenceValue;
  967. }
  968. public FieldDeserializer getFieldDeserializer() {
  969. return fieldDeserializer;
  970. }
  971. public void setFieldDeserializer(FieldDeserializer fieldDeserializer) {
  972. this.fieldDeserializer = fieldDeserializer;
  973. }
  974. public ParseContext getOwnerContext() {
  975. return ownerContext;
  976. }
  977. public void setOwnerContext(ParseContext ownerContext) {
  978. this.ownerContext = ownerContext;
  979. }
  980. }
  981. }