use of com.alibaba.fastjson.annotation.JSONType in project fastjson by alibaba.
the class ParserConfig method getDeserializer.
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
ObjectDeserializer deserializer = get(type);
if (deserializer == null && type instanceof ParameterizedTypeImpl) {
Type innerType = TypeReference.intern((ParameterizedTypeImpl) type);
deserializer = get(innerType);
}
if (deserializer != null) {
return deserializer;
}
if (type == null) {
type = clazz;
}
deserializer = get(type);
if (deserializer != null) {
return deserializer;
}
{
JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class);
if (annotation != null) {
Class<?> mappingTo = annotation.mappingTo();
if (mappingTo != Void.class) {
return getDeserializer(mappingTo, mappingTo);
}
}
}
if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) {
deserializer = get(clazz);
}
if (deserializer != null) {
return deserializer;
}
for (Module module : modules) {
deserializer = module.createDeserializer(this, clazz);
if (deserializer != null) {
putDeserializer(type, deserializer);
return deserializer;
}
}
String className = clazz.getName();
className = className.replace('$', '.');
if (//
className.startsWith("java.awt.") && AwtCodec.support(clazz)) {
if (!awtError) {
String[] names = new String[] { "java.awt.Point", "java.awt.Font", "java.awt.Rectangle", "java.awt.Color" };
try {
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = AwtCodec.instance);
return deserializer;
}
}
} catch (Throwable e) {
// skip
awtError = true;
}
deserializer = AwtCodec.instance;
}
}
if (!jdk8Error) {
try {
if (className.startsWith("java.time.")) {
String[] names = new String[] { "java.time.LocalDateTime", "java.time.LocalDate", "java.time.LocalTime", "java.time.ZonedDateTime", "java.time.OffsetDateTime", "java.time.OffsetTime", "java.time.ZoneOffset", "java.time.ZoneRegion", "java.time.ZoneId", "java.time.Period", "java.time.Duration", "java.time.Instant" };
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = Jdk8DateCodec.instance);
return deserializer;
}
}
} else if (className.startsWith("java.util.Optional")) {
String[] names = new String[] { "java.util.Optional", "java.util.OptionalDouble", "java.util.OptionalInt", "java.util.OptionalLong" };
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = OptionalCodec.instance);
return deserializer;
}
}
}
} catch (Throwable e) {
// skip
jdk8Error = true;
}
}
if (!jodaError) {
try {
if (className.startsWith("org.joda.time.")) {
String[] names = new String[] { "org.joda.time.DateTime", "org.joda.time.LocalDate", "org.joda.time.LocalDateTime", "org.joda.time.LocalTime", "org.joda.time.Instant", "org.joda.time.Period", "org.joda.time.Duration", "org.joda.time.DateTimeZone", "org.joda.time.format.DateTimeFormatter" };
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = JodaCodec.instance);
return deserializer;
}
}
}
} catch (Throwable e) {
// skip
jodaError = true;
}
}
if (//
(!guavaError) && className.startsWith("com.google.common.collect.")) {
try {
String[] names = new String[] { "com.google.common.collect.HashMultimap", "com.google.common.collect.LinkedListMultimap", "com.google.common.collect.LinkedHashMultimap", "com.google.common.collect.ArrayListMultimap", "com.google.common.collect.TreeMultimap" };
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = GuavaCodec.instance);
return deserializer;
}
}
} catch (ClassNotFoundException e) {
// skip
guavaError = true;
}
}
if (className.equals("java.nio.ByteBuffer")) {
putDeserializer(clazz, deserializer = ByteBufferCodec.instance);
}
if (className.equals("java.nio.file.Path")) {
putDeserializer(clazz, deserializer = MiscCodec.instance);
}
if (clazz == Map.Entry.class) {
putDeserializer(clazz, deserializer = MiscCodec.instance);
}
if (className.equals("org.javamoney.moneta.Money")) {
putDeserializer(clazz, deserializer = MonetaCodec.instance);
}
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) {
for (Type forType : autowired.getAutowiredFor()) {
putDeserializer(forType, autowired);
}
}
} catch (Exception ex) {
// skip
}
if (deserializer == null) {
deserializer = get(type);
}
if (deserializer != null) {
return deserializer;
}
if (clazz.isEnum()) {
if (jacksonCompatible) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (TypeUtils.isJacksonCreator(method)) {
deserializer = createJavaBeanDeserializer(clazz, type);
putDeserializer(type, deserializer);
return deserializer;
}
}
}
Class mixInType = (Class) JSON.getMixInAnnotations(clazz);
Class<?> deserClass = null;
JSONType jsonType = TypeUtils.getAnnotation(mixInType != null ? mixInType : clazz, JSONType.class);
if (jsonType != null) {
deserClass = jsonType.deserializer();
try {
deserializer = (ObjectDeserializer) deserClass.newInstance();
putDeserializer(clazz, deserializer);
return deserializer;
} catch (Throwable error) {
// skip
}
}
Method jsonCreatorMethod = null;
if (mixInType != null) {
Method mixedCreator = getEnumCreator(mixInType, clazz);
if (mixedCreator != null) {
try {
jsonCreatorMethod = clazz.getMethod(mixedCreator.getName(), mixedCreator.getParameterTypes());
} catch (Exception e) {
// skip
}
}
} else {
jsonCreatorMethod = getEnumCreator(clazz, clazz);
}
if (jsonCreatorMethod != null) {
deserializer = new EnumCreatorDeserializer(jsonCreatorMethod);
putDeserializer(clazz, deserializer);
return deserializer;
}
deserializer = getEnumDeserializer(clazz);
} else if (clazz.isArray()) {
deserializer = ObjectArrayCodec.instance;
} else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) {
deserializer = CollectionCodec.instance;
} else if (Collection.class.isAssignableFrom(clazz)) {
deserializer = CollectionCodec.instance;
} else if (Map.class.isAssignableFrom(clazz)) {
deserializer = MapDeserializer.instance;
} else if (Throwable.class.isAssignableFrom(clazz)) {
deserializer = new ThrowableDeserializer(this, clazz);
} else if (PropertyProcessable.class.isAssignableFrom(clazz)) {
deserializer = new PropertyProcessableDeserializer((Class<PropertyProcessable>) clazz);
} else if (clazz == InetAddress.class) {
deserializer = MiscCodec.instance;
} else {
deserializer = createJavaBeanDeserializer(clazz, type);
}
putDeserializer(type, deserializer);
return deserializer;
}
use of com.alibaba.fastjson.annotation.JSONType in project fastjson by alibaba.
the class JavaBeanInfo method build.
public static //
JavaBeanInfo build(//
Class<?> clazz, //
Type type, //
PropertyNamingStrategy propertyNamingStrategy, //
boolean fieldBased, boolean compatibleWithJavaBean, boolean jacksonCompatible) {
JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class);
if (jsonType != null) {
PropertyNamingStrategy jsonTypeNaming = jsonType.naming();
if (jsonTypeNaming != null && jsonTypeNaming != PropertyNamingStrategy.CamelCase) {
propertyNamingStrategy = jsonTypeNaming;
}
}
Class<?> builderClass = getBuilderClass(clazz, jsonType);
Field[] declaredFields = clazz.getDeclaredFields();
Method[] methods = clazz.getMethods();
Map<TypeVariable, Type> genericInfo = buildGenericInfo(clazz);
boolean kotlin = TypeUtils.isKotlin(clazz);
Constructor[] constructors = clazz.getDeclaredConstructors();
Constructor<?> defaultConstructor = null;
if ((!kotlin) || constructors.length == 1) {
if (builderClass == null) {
defaultConstructor = getDefaultConstructor(clazz, constructors);
} else {
defaultConstructor = getDefaultConstructor(builderClass, builderClass.getDeclaredConstructors());
}
}
Constructor<?> creatorConstructor = null;
Method buildMethod = null;
Method factoryMethod = null;
List<FieldInfo> fieldList = new ArrayList<FieldInfo>();
if (fieldBased) {
for (Class<?> currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) {
Field[] fields = currentClass.getDeclaredFields();
computeFields(clazz, type, propertyNamingStrategy, fieldList, fields);
}
if (defaultConstructor != null) {
TypeUtils.setAccessible(defaultConstructor);
}
return new JavaBeanInfo(clazz, builderClass, defaultConstructor, null, factoryMethod, buildMethod, jsonType, fieldList);
}
boolean isInterfaceOrAbstract = clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers());
if ((defaultConstructor == null && builderClass == null) || isInterfaceOrAbstract) {
Type mixInType = JSON.getMixInAnnotations(clazz);
if (mixInType instanceof Class) {
Constructor<?>[] mixInConstructors = ((Class<?>) mixInType).getConstructors();
Constructor<?> mixInCreator = getCreatorConstructor(mixInConstructors);
if (mixInCreator != null) {
try {
creatorConstructor = clazz.getConstructor(mixInCreator.getParameterTypes());
} catch (NoSuchMethodException e) {
// skip
}
}
}
if (creatorConstructor == null) {
creatorConstructor = getCreatorConstructor(constructors);
}
if (creatorConstructor != null && !isInterfaceOrAbstract) {
// 基于标记 JSONCreator 注解的构造方法
TypeUtils.setAccessible(creatorConstructor);
Class<?>[] types = creatorConstructor.getParameterTypes();
String[] lookupParameterNames = null;
if (types.length > 0) {
Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor);
for (int i = 0; i < types.length && i < paramAnnotationArrays.length; ++i) {
Annotation[] paramAnnotations = paramAnnotationArrays[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
Class<?> fieldClass = types[i];
Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
String fieldName = null;
Field field = null;
int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
if (fieldAnnotation != null) {
field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields);
ordinal = fieldAnnotation.ordinal();
serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
fieldName = fieldAnnotation.name();
}
if (fieldName == null || fieldName.length() == 0) {
if (lookupParameterNames == null) {
lookupParameterNames = ASMUtils.lookupParameterNames(creatorConstructor);
}
fieldName = lookupParameterNames[i];
}
if (field == null) {
if (lookupParameterNames == null) {
if (kotlin) {
lookupParameterNames = TypeUtils.getKoltinConstructorParameters(clazz);
} else {
lookupParameterNames = ASMUtils.lookupParameterNames(creatorConstructor);
}
}
if (lookupParameterNames.length > i) {
String parameterName = lookupParameterNames[i];
field = TypeUtils.getField(clazz, parameterName, declaredFields);
}
}
FieldInfo fieldInfo = new FieldInfo(fieldName, clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
add(fieldList, fieldInfo);
}
}
// return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList);
} else if ((factoryMethod = getFactoryMethod(clazz, methods, jacksonCompatible)) != null) {
TypeUtils.setAccessible(factoryMethod);
String[] lookupParameterNames = null;
Class<?>[] types = factoryMethod.getParameterTypes();
if (types.length > 0) {
Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(factoryMethod);
for (int i = 0; i < types.length; ++i) {
Annotation[] paramAnnotations = paramAnnotationArrays[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
if (fieldAnnotation == null && !(jacksonCompatible && TypeUtils.isJacksonCreator(factoryMethod))) {
throw new JSONException("illegal json creator");
}
String fieldName = null;
int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
if (fieldAnnotation != null) {
fieldName = fieldAnnotation.name();
ordinal = fieldAnnotation.ordinal();
serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
}
if (fieldName == null || fieldName.length() == 0) {
if (lookupParameterNames == null) {
lookupParameterNames = ASMUtils.lookupParameterNames(factoryMethod);
}
fieldName = lookupParameterNames[i];
}
Class<?> fieldClass = types[i];
Type fieldType = factoryMethod.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, fieldName, declaredFields);
FieldInfo fieldInfo = new FieldInfo(fieldName, clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
add(fieldList, fieldInfo);
}
return new JavaBeanInfo(clazz, builderClass, null, null, factoryMethod, null, jsonType, fieldList);
}
} else if (!isInterfaceOrAbstract) {
String className = clazz.getName();
String[] paramNames = null;
if (kotlin && constructors.length > 0) {
paramNames = TypeUtils.getKoltinConstructorParameters(clazz);
creatorConstructor = TypeUtils.getKotlinConstructor(constructors, paramNames);
TypeUtils.setAccessible(creatorConstructor);
} else {
for (Constructor constructor : constructors) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
if (className.equals("org.springframework.security.web.authentication.WebAuthenticationDetails")) {
if (parameterTypes.length == 2 && parameterTypes[0] == String.class && parameterTypes[1] == String.class) {
creatorConstructor = constructor;
creatorConstructor.setAccessible(true);
paramNames = ASMUtils.lookupParameterNames(constructor);
break;
} else {
continue;
}
}
if (className.equals("org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken")) {
if (parameterTypes.length == 3 && parameterTypes[0] == Object.class && parameterTypes[1] == Object.class && parameterTypes[2] == Collection.class) {
creatorConstructor = constructor;
creatorConstructor.setAccessible(true);
paramNames = new String[] { "principal", "credentials", "authorities" };
break;
} else {
continue;
}
}
if (className.equals("org.springframework.security.core.authority.SimpleGrantedAuthority")) {
if (parameterTypes.length == 1 && parameterTypes[0] == String.class) {
creatorConstructor = constructor;
paramNames = new String[] { "authority" };
break;
} else {
continue;
}
}
//
boolean is_public = (constructor.getModifiers() & Modifier.PUBLIC) != 0;
if (!is_public) {
continue;
}
String[] lookupParameterNames = ASMUtils.lookupParameterNames(constructor);
if (lookupParameterNames == null || lookupParameterNames.length == 0) {
continue;
}
if (creatorConstructor != null && paramNames != null && lookupParameterNames.length <= paramNames.length) {
continue;
}
paramNames = lookupParameterNames;
creatorConstructor = constructor;
}
}
Class<?>[] types = null;
if (paramNames != null) {
types = creatorConstructor.getParameterTypes();
}
if (paramNames != null && types.length == paramNames.length) {
Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor);
for (int i = 0; i < types.length; ++i) {
Annotation[] paramAnnotations = paramAnnotationArrays[i];
String paramName = paramNames[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
Class<?> fieldClass = types[i];
Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, paramName, declaredFields);
if (field != null) {
if (fieldAnnotation == null) {
fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class);
}
}
final int ordinal, serialzeFeatures, parserFeatures;
if (fieldAnnotation == null) {
ordinal = 0;
serialzeFeatures = 0;
if ("org.springframework.security.core.userdetails.User".equals(className) && "password".equals(paramName)) {
parserFeatures = Feature.InitStringFieldAsEmpty.mask;
} else {
parserFeatures = 0;
}
} else {
String nameAnnotated = fieldAnnotation.name();
if (nameAnnotated.length() != 0) {
paramName = nameAnnotated;
}
ordinal = fieldAnnotation.ordinal();
serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
}
FieldInfo fieldInfo = new FieldInfo(paramName, clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
add(fieldList, fieldInfo);
}
if ((!kotlin) && !clazz.getName().equals("javax.servlet.http.Cookie")) {
return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList);
}
} else {
throw new JSONException("default constructor not found. " + clazz);
}
}
}
if (defaultConstructor != null) {
TypeUtils.setAccessible(defaultConstructor);
}
if (builderClass != null) {
String withPrefix = null;
JSONPOJOBuilder builderAnno = TypeUtils.getAnnotation(builderClass, JSONPOJOBuilder.class);
if (builderAnno != null) {
withPrefix = builderAnno.withPrefix();
}
if (withPrefix == null) {
withPrefix = "with";
}
for (Method method : builderClass.getMethods()) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
if (!(method.getReturnType().equals(builderClass))) {
continue;
}
int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
if (annotation == null) {
annotation = TypeUtils.getSuperMethodAnnotation(clazz, method);
}
if (annotation != null) {
if (!annotation.deserialize()) {
continue;
}
ordinal = annotation.ordinal();
serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures());
parserFeatures = Feature.of(annotation.parseFeatures());
if (annotation.name().length() != 0) {
String propertyName = annotation.name();
add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null, genericInfo));
continue;
}
}
String methodName = method.getName();
StringBuilder properNameBuilder;
if (methodName.startsWith("set") && methodName.length() > 3) {
properNameBuilder = new StringBuilder(methodName.substring(3));
} else {
if (withPrefix.length() == 0) {
properNameBuilder = new StringBuilder(methodName);
} else {
if (!methodName.startsWith(withPrefix)) {
continue;
}
if (methodName.length() <= withPrefix.length()) {
continue;
}
properNameBuilder = new StringBuilder(methodName.substring(withPrefix.length()));
}
}
char c0 = properNameBuilder.charAt(0);
if (withPrefix.length() != 0 && !Character.isUpperCase(c0)) {
continue;
}
properNameBuilder.setCharAt(0, Character.toLowerCase(c0));
String propertyName = properNameBuilder.toString();
add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null, genericInfo));
}
if (builderClass != null) {
JSONPOJOBuilder builderAnnotation = TypeUtils.getAnnotation(builderClass, JSONPOJOBuilder.class);
String buildMethodName = null;
if (builderAnnotation != null) {
buildMethodName = builderAnnotation.buildMethod();
}
if (buildMethodName == null || buildMethodName.length() == 0) {
buildMethodName = "build";
}
try {
buildMethod = builderClass.getMethod(buildMethodName);
} catch (NoSuchMethodException e) {
// skip
} catch (SecurityException e) {
// skip
}
if (buildMethod == null) {
try {
buildMethod = builderClass.getMethod("create");
} catch (NoSuchMethodException e) {
// skip
} catch (SecurityException e) {
// skip
}
}
if (buildMethod == null) {
throw new JSONException("buildMethod not found.");
}
TypeUtils.setAccessible(buildMethod);
}
}
for (Method method : methods) {
//
int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
String methodName = method.getName();
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
// support builder set
Class<?> returnType = method.getReturnType();
if (!(returnType.equals(Void.TYPE) || returnType.equals(method.getDeclaringClass()))) {
continue;
}
if (method.getDeclaringClass() == Object.class) {
continue;
}
Class<?>[] types = method.getParameterTypes();
if (types.length == 0 || types.length > 2) {
continue;
}
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
if (annotation != null && types.length == 2 && types[0] == String.class && types[1] == Object.class) {
add(fieldList, new FieldInfo("", method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null, genericInfo));
continue;
}
if (types.length != 1) {
continue;
}
if (annotation == null) {
annotation = TypeUtils.getSuperMethodAnnotation(clazz, method);
}
if (annotation == null && methodName.length() < 4) {
continue;
}
if (annotation != null) {
if (!annotation.deserialize()) {
continue;
}
ordinal = annotation.ordinal();
serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures());
parserFeatures = Feature.of(annotation.parseFeatures());
if (annotation.name().length() != 0) {
String propertyName = annotation.name();
add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null, genericInfo));
continue;
}
}
if (annotation == null && !methodName.startsWith("set") || builderClass != null) {
// TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解?
continue;
}
char c3 = methodName.charAt(3);
String propertyName;
Field field = null;
// 用于存储KotlinBean中所有的get方法, 方便后续判断
List<String> getMethodNameList = null;
if (kotlin) {
getMethodNameList = new ArrayList();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().startsWith("get")) {
getMethodNameList.add(methods[i].getName());
}
}
}
if (//
Character.isUpperCase(c3) || // for unicode method name
c3 > 512) {
// 因此如果是kotlin的话还需要进行不一样的判断, 判断的方式是通过get方法进行判断, isAbc的get方法名为isAbc(), abc的get方法名为getAbc()
if (kotlin) {
String getMethodName = "g" + methodName.substring(1);
propertyName = TypeUtils.getPropertyNameByMethodName(getMethodName);
} else {
if (TypeUtils.compatibleWithJavaBean) {
propertyName = TypeUtils.decapitalize(methodName.substring(3));
} else {
propertyName = TypeUtils.getPropertyNameByMethodName(methodName);
}
}
} else if (c3 == '_') {
// 因此如果是kotlin的话还需要进行不一样的判断, 判断的方式是通过get方法进行判断, is_abc的get方法名为is_abc(), _abc的get方法名为get_abc()
if (kotlin) {
String getMethodName = "g" + methodName.substring(1);
if (getMethodNameList.contains(getMethodName)) {
propertyName = methodName.substring(3);
} else {
propertyName = "is" + methodName.substring(3);
}
field = TypeUtils.getField(clazz, propertyName, declaredFields);
} else {
propertyName = methodName.substring(4);
field = TypeUtils.getField(clazz, propertyName, declaredFields);
if (field == null) {
String temp = propertyName;
propertyName = methodName.substring(3);
field = TypeUtils.getField(clazz, propertyName, declaredFields);
if (field == null) {
// 减少修改代码带来的影响
propertyName = temp;
}
}
}
} else if (c3 == 'f') {
propertyName = methodName.substring(3);
} else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) {
propertyName = TypeUtils.decapitalize(methodName.substring(3));
} else {
propertyName = methodName.substring(3);
field = TypeUtils.getField(clazz, propertyName, declaredFields);
if (field == null) {
continue;
}
}
if (field == null) {
field = TypeUtils.getField(clazz, propertyName, declaredFields);
}
if (field == null && types[0] == boolean.class) {
String isFieldName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
field = TypeUtils.getField(clazz, isFieldName, declaredFields);
}
JSONField fieldAnnotation = null;
if (field != null) {
fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class);
if (fieldAnnotation != null) {
if (!fieldAnnotation.deserialize()) {
continue;
}
ordinal = fieldAnnotation.ordinal();
serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
if (fieldAnnotation.name().length() != 0) {
propertyName = fieldAnnotation.name();
add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null, genericInfo));
continue;
}
}
}
if (propertyNamingStrategy != null) {
propertyName = propertyNamingStrategy.translate(propertyName);
}
add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null, genericInfo));
}
Field[] fields = clazz.getFields();
computeFields(clazz, type, propertyNamingStrategy, fieldList, fields);
for (Method method : clazz.getMethods()) {
// getter methods
String methodName = method.getName();
if (methodName.length() < 4) {
continue;
}
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
if (builderClass == null && methodName.startsWith("get") && Character.isUpperCase(methodName.charAt(3))) {
if (method.getParameterTypes().length != 0) {
continue;
}
if (//
Collection.class.isAssignableFrom(method.getReturnType()) || //
Map.class.isAssignableFrom(method.getReturnType()) || //
AtomicBoolean.class == method.getReturnType() || //
AtomicInteger.class == method.getReturnType() || //
AtomicLong.class == method.getReturnType()) {
String propertyName;
Field collectionField = null;
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
if (annotation != null && annotation.deserialize()) {
continue;
}
if (annotation != null && annotation.name().length() > 0) {
propertyName = annotation.name();
} else {
propertyName = TypeUtils.getPropertyNameByMethodName(methodName);
Field field = TypeUtils.getField(clazz, propertyName, declaredFields);
if (field != null) {
JSONField fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class);
if (fieldAnnotation != null && !fieldAnnotation.deserialize()) {
continue;
}
if (Collection.class.isAssignableFrom(method.getReturnType()) || Map.class.isAssignableFrom(method.getReturnType())) {
collectionField = field;
}
}
}
if (propertyNamingStrategy != null) {
propertyName = propertyNamingStrategy.translate(propertyName);
}
FieldInfo fieldInfo = getField(fieldList, propertyName);
if (fieldInfo != null) {
continue;
}
add(fieldList, new FieldInfo(propertyName, method, collectionField, clazz, type, 0, 0, 0, annotation, null, null, genericInfo));
}
}
}
if (fieldList.size() == 0) {
if (TypeUtils.isXmlField(clazz)) {
fieldBased = true;
}
if (fieldBased) {
for (Class<?> currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) {
computeFields(clazz, type, propertyNamingStrategy, fieldList, declaredFields);
}
}
}
return new JavaBeanInfo(clazz, builderClass, defaultConstructor, creatorConstructor, factoryMethod, buildMethod, jsonType, fieldList);
}
use of com.alibaba.fastjson.annotation.JSONType in project fastjson by alibaba.
the class TypeUtils method computeGetters.
public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap, boolean sorted) {
JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class);
Map<String, Field> fieldCacheMap = new HashMap<String, Field>();
ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap);
return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase);
}
use of com.alibaba.fastjson.annotation.JSONType in project fastjson by alibaba.
the class ParserConfigBug569 method getDeserializer.
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
com.alibaba.fastjson.util.IdentityHashMap<Type, ObjectDeserializer> deserializers = super.getDeserializers();
ObjectDeserializer deserializer = deserializers.get(type);
if (deserializer != null) {
return deserializer;
}
if (type == null) {
type = clazz;
}
deserializer = deserializers.get(type);
if (deserializer != null) {
return deserializer;
}
{
JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class);
if (annotation != null) {
Class<?> mappingTo = annotation.mappingTo();
if (mappingTo != Void.class) {
return getDeserializer(mappingTo, mappingTo);
}
}
}
if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) {
deserializer = deserializers.get(clazz);
}
if (deserializer != null) {
return deserializer;
}
String className = clazz.getName();
className = className.replace('$', '.');
for (int i = 0; i < denyList.length; ++i) {
String deny = denyList[i];
if (className.startsWith(deny)) {
throw new JSONException("parser deny : " + className);
}
}
if (//
className.startsWith("java.awt.") && AwtCodec.support(clazz)) {
if (!awtError) {
try {
deserializers.put(Class.forName("java.awt.Point"), AwtCodec.instance);
deserializers.put(Class.forName("java.awt.Font"), AwtCodec.instance);
deserializers.put(Class.forName("java.awt.Rectangle"), AwtCodec.instance);
deserializers.put(Class.forName("java.awt.Color"), AwtCodec.instance);
} catch (Throwable e) {
// skip
awtError = true;
}
deserializer = AwtCodec.instance;
}
}
if (!jdk8Error) {
try {
if (className.startsWith("java.time.")) {
deserializers.put(Class.forName("java.time.LocalDateTime"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.LocalDate"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.LocalTime"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.ZonedDateTime"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.OffsetDateTime"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.OffsetTime"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.ZoneOffset"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.ZoneRegion"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.ZoneId"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.Period"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.Duration"), Jdk8DateCodec.instance);
deserializers.put(Class.forName("java.time.Instant"), Jdk8DateCodec.instance);
deserializer = deserializers.get(clazz);
} else if (className.startsWith("java.util.Optional")) {
deserializers.put(Class.forName("java.util.Optional"), OptionalCodec.instance);
deserializers.put(Class.forName("java.util.OptionalDouble"), OptionalCodec.instance);
deserializers.put(Class.forName("java.util.OptionalInt"), OptionalCodec.instance);
deserializers.put(Class.forName("java.util.OptionalLong"), OptionalCodec.instance);
deserializer = deserializers.get(clazz);
}
} catch (Throwable e) {
// skip
jdk8Error = true;
}
}
if (className.equals("java.nio.file.Path")) {
deserializers.put(clazz, MiscCodec.instance);
}
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) {
for (Type forType : autowired.getAutowiredFor()) {
deserializers.put(forType, autowired);
}
}
} catch (Exception ex) {
// skip
}
if (deserializer == null) {
deserializer = deserializers.get(type);
}
if (deserializer != null) {
return deserializer;
}
if (clazz.isEnum()) {
deserializer = new EnumDeserializer(clazz);
} else if (clazz.isArray()) {
deserializer = ObjectArrayCodec.instance;
} else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) {
deserializer = CollectionCodec.instance;
} else if (Collection.class.isAssignableFrom(clazz)) {
deserializer = CollectionCodec.instance;
} else if (Map.class.isAssignableFrom(clazz)) {
deserializer = MapDeserializer.instance;
} else if (Throwable.class.isAssignableFrom(clazz)) {
deserializer = new ThrowableDeserializer(this, clazz);
} else {
deserializer = createJavaBeanDeserializer(clazz, type);
}
putDeserializer(type, deserializer);
return deserializer;
}
use of com.alibaba.fastjson.annotation.JSONType in project uavstack by uavorg.
the class ASMSerializerFactory method _if_write_null.
private void _if_write_null(MethodVisitor mw, FieldInfo fieldInfo, Context context) {
Class<?> propertyClass = fieldInfo.fieldClass;
Label _if = new Label();
Label _else = new Label();
Label _write_null = new Label();
Label _end_if = new Label();
mw.visitLabel(_if);
JSONField annotation = fieldInfo.getAnnotation();
int features = 0;
if (annotation != null) {
features = SerializerFeature.of(annotation.serialzeFeatures());
}
JSONType jsonType = context.beanInfo.jsonType;
if (jsonType != null) {
features |= SerializerFeature.of(jsonType.serialzeFeatures());
}
int writeNullFeatures;
if (propertyClass == String.class) {
writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() | SerializerFeature.WriteNullStringAsEmpty.getMask();
} else if (Number.class.isAssignableFrom(propertyClass)) {
writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() | SerializerFeature.WriteNullNumberAsZero.getMask();
} else if (Collection.class.isAssignableFrom(propertyClass)) {
writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() | SerializerFeature.WriteNullListAsEmpty.getMask();
} else if (Boolean.class == propertyClass) {
writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() | SerializerFeature.WriteNullBooleanAsFalse.getMask();
} else {
writeNullFeatures = SerializerFeature.WRITE_MAP_NULL_FEATURES;
}
if ((features & writeNullFeatures) == 0) {
mw.visitVarInsn(ALOAD, context.var("out"));
mw.visitLdcInsn(writeNullFeatures);
mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z");
mw.visitJumpInsn(IFEQ, _else);
}
mw.visitLabel(_write_null);
mw.visitVarInsn(ALOAD, context.var("out"));
mw.visitVarInsn(ILOAD, context.var("seperator"));
mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V");
_writeFieldName(mw, context);
mw.visitVarInsn(ALOAD, context.var("out"));
mw.visitLdcInsn(features);
if (propertyClass == String.class || propertyClass == Character.class) {
mw.visitLdcInsn(SerializerFeature.WriteNullStringAsEmpty.mask);
} else if (Number.class.isAssignableFrom(propertyClass)) {
mw.visitLdcInsn(SerializerFeature.WriteNullNumberAsZero.mask);
} else if (propertyClass == Boolean.class) {
mw.visitLdcInsn(SerializerFeature.WriteNullBooleanAsFalse.mask);
} else if (Collection.class.isAssignableFrom(propertyClass) || propertyClass.isArray()) {
mw.visitLdcInsn(SerializerFeature.WriteNullListAsEmpty.mask);
} else {
mw.visitLdcInsn(0);
}
mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "(II)V");
// seperator = ',';
_seperator(mw, context);
mw.visitJumpInsn(GOTO, _end_if);
mw.visitLabel(_else);
mw.visitLabel(_end_if);
}
Aggregations