Skip to content

Commit

Permalink
improved performance
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Apr 17, 2016
1 parent 15d2d7b commit 952723a
Showing 1 changed file with 13 additions and 30 deletions.
@@ -1,9 +1,6 @@
package com.alibaba.fastjson.parser.deserializer;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.parser.DefaultJSONParser;
Expand All @@ -13,53 +10,39 @@
@SuppressWarnings("rawtypes")
public class EnumDeserializer implements ObjectDeserializer {

private final Class<?> enumClass;

private final Map<Integer, Enum> ordinalMap = new HashMap<Integer, Enum>();
private final Map<String, Enum> nameMap = new HashMap<String, Enum>();
private final Class<?> enumClass;
private final Enum[] values;

public EnumDeserializer(Class<?> enumClass){
this.enumClass = enumClass;

try {
Method valueMethod = enumClass.getMethod("values");
Object[] values = (Object[]) valueMethod.invoke(null);
for (Object value : values) {
Enum e = (Enum) value;
ordinalMap.put(e.ordinal(), e);
nameMap.put(e.name(), e);
}
} catch (Exception ex) {
throw new JSONException("init enum values error, " + enumClass.getName());
}
values = (Enum[]) enumClass.getEnumConstants();
}

@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
try {
Object value;
final JSONLexer lexer = parser.lexer;
if (lexer.token() == JSONToken.LITERAL_INT) {
value = lexer.intValue();
final int token = lexer.token();
if (token == JSONToken.LITERAL_INT) {
int intValue = lexer.intValue();
lexer.nextToken(JSONToken.COMMA);

T e = (T) ordinalMap.get(value);
if (e == null) {
throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value);
if (intValue < 0 || intValue > values.length) {
throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + intValue);
}
return e;
} else if (lexer.token() == JSONToken.LITERAL_STRING) {

return (T) values[intValue];
} else if (token == JSONToken.LITERAL_STRING) {
String strVal = lexer.stringVal();
lexer.nextToken(JSONToken.COMMA);

if (strVal.length() == 0) {
return (T) null;
}

value = nameMap.get(strVal);

return (T) Enum.valueOf((Class<Enum>) enumClass, strVal);
} else if (lexer.token() == JSONToken.NULL) {
} else if (token == JSONToken.NULL) {
value = null;
lexer.nextToken(JSONToken.COMMA);

Expand All @@ -71,7 +54,7 @@ public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value);
} catch (JSONException e) {
throw e;
} catch (Throwable e) {
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
Expand Down

0 comments on commit 952723a

Please sign in to comment.