PageRenderTime 45ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/xiejuntao/xdesktop
Java | 82 lines | 67 code | 15 blank | 0 comment | 14 complexity | f56d4f9a91a0f58e55a59b720ce53ab7 MD5 | raw file
  1. package com.alibaba.fastjson.parser.deserializer;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Type;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import com.alibaba.fastjson.JSONException;
  7. import com.alibaba.fastjson.parser.DefaultJSONParser;
  8. import com.alibaba.fastjson.parser.JSONLexer;
  9. import com.alibaba.fastjson.parser.JSONToken;
  10. @SuppressWarnings("rawtypes")
  11. public class EnumDeserializer implements ObjectDeserializer {
  12. private final Class<?> enumClass;
  13. private final Map<Integer, Enum> ordinalMap = new HashMap<Integer, Enum>();
  14. private final Map<String, Enum> nameMap = new HashMap<String, Enum>();
  15. public EnumDeserializer(Class<?> enumClass){
  16. this.enumClass = enumClass;
  17. try {
  18. Method valueMethod = enumClass.getMethod("values");
  19. Object[] values = (Object[]) valueMethod.invoke(null);
  20. for (Object value : values) {
  21. Enum e = (Enum) value;
  22. ordinalMap.put(e.ordinal(), e);
  23. nameMap.put(e.name(), e);
  24. }
  25. } catch (Exception ex) {
  26. throw new JSONException("init enum values error, " + enumClass.getName());
  27. }
  28. }
  29. @SuppressWarnings("unchecked")
  30. public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
  31. try {
  32. Object value;
  33. final JSONLexer lexer = parser.getLexer();
  34. if (lexer.token() == JSONToken.LITERAL_INT) {
  35. value = lexer.intValue();
  36. lexer.nextToken(JSONToken.COMMA);
  37. T e = (T) ordinalMap.get(value);
  38. if (e == null) {
  39. throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value);
  40. }
  41. return e;
  42. } else if (lexer.token() == JSONToken.LITERAL_STRING) {
  43. String strVal = lexer.stringVal();
  44. lexer.nextToken(JSONToken.COMMA);
  45. if (strVal.length() == 0) {
  46. return (T) null;
  47. }
  48. value = nameMap.get(strVal);
  49. return (T) Enum.valueOf((Class<Enum>) enumClass, strVal);
  50. } else if (lexer.token() == JSONToken.NULL) {
  51. value = null;
  52. lexer.nextToken(JSONToken.COMMA);
  53. return null;
  54. } else {
  55. value = parser.parse();
  56. }
  57. throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value);
  58. } catch (JSONException e) {
  59. throw e;
  60. } catch (Throwable e) {
  61. throw new JSONException(e.getMessage(), e);
  62. }
  63. }
  64. public int getFastMatchToken() {
  65. return JSONToken.LITERAL_INT;
  66. }
  67. }