PageRenderTime 38ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/parser/deserializer/CollectionDeserializer.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 70 lines | 58 code | 12 blank | 0 comment | 17 complexity | 2cf69f91e6d25999e48493a283d2992c MD5 | raw file
  1. package com.alibaba.fastjson.parser.deserializer;
  2. import java.lang.reflect.ParameterizedType;
  3. import java.lang.reflect.Type;
  4. import java.util.AbstractCollection;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.HashSet;
  8. import java.util.LinkedHashSet;
  9. import com.alibaba.fastjson.JSONException;
  10. import com.alibaba.fastjson.parser.DefaultJSONParser;
  11. import com.alibaba.fastjson.parser.JSONToken;
  12. public class CollectionDeserializer implements ObjectDeserializer {
  13. public final static CollectionDeserializer instance = new CollectionDeserializer();
  14. @SuppressWarnings({ "unchecked", "rawtypes" })
  15. public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
  16. if (parser.getLexer().token() == JSONToken.NULL) {
  17. parser.getLexer().nextToken(JSONToken.COMMA);
  18. return null;
  19. }
  20. Class<?> rawClass = getRawClass(type);
  21. Collection list;
  22. if (rawClass == AbstractCollection.class) {
  23. list = new ArrayList();
  24. } else if (rawClass.isAssignableFrom(HashSet.class)) {
  25. list = new HashSet();
  26. } else if (rawClass.isAssignableFrom(LinkedHashSet.class)) {
  27. list = new LinkedHashSet();
  28. } else if (rawClass.isAssignableFrom(ArrayList.class)) {
  29. list = new ArrayList();
  30. } else {
  31. try {
  32. list = (Collection) rawClass.newInstance();
  33. } catch (Exception e) {
  34. throw new JSONException("create instane error, class " + rawClass.getName());
  35. }
  36. }
  37. Type itemType;
  38. if (type instanceof ParameterizedType) {
  39. itemType = ((ParameterizedType) type).getActualTypeArguments()[0];
  40. } else {
  41. itemType = Object.class;
  42. }
  43. parser.parseArray(itemType, list, fieldName);
  44. return (T) list;
  45. }
  46. public Class<?> getRawClass(Type type) {
  47. if (type instanceof Class<?>) {
  48. return (Class<?>) type;
  49. } else if (type instanceof ParameterizedType) {
  50. return getRawClass(((ParameterizedType) type).getRawType());
  51. } else {
  52. throw new JSONException("TODO");
  53. }
  54. }
  55. public int getFastMatchToken() {
  56. return JSONToken.LBRACKET;
  57. }
  58. }