Search in sources :

Example 1 with JSONField

use of com.alibaba.fastjson.annotation.JSONField in project fastjson by alibaba.

the class ParserConfig method createJavaBeanDeserializer.

public ObjectDeserializer createJavaBeanDeserializer(Class<?> clazz, Type type) {
    boolean asmEnable = this.asmEnable;
    if (asmEnable) {
        JSONType jsonType = clazz.getAnnotation(JSONType.class);
        if (jsonType != null) {
            Class<?> deserializerClass = jsonType.deserializer();
            if (deserializerClass != Void.class) {
                try {
                    Object deseralizer = deserializerClass.newInstance();
                    if (deseralizer instanceof ObjectDeserializer) {
                        return (ObjectDeserializer) deseralizer;
                    }
                } catch (Throwable e) {
                // skip
                }
            }
            asmEnable = jsonType.asm();
        }
        if (asmEnable) {
            Class<?> superClass = JavaBeanInfo.getBuilderClass(jsonType);
            if (superClass == null) {
                superClass = clazz;
            }
            for (; ; ) {
                if (!Modifier.isPublic(superClass.getModifiers())) {
                    asmEnable = false;
                    break;
                }
                superClass = superClass.getSuperclass();
                if (superClass == Object.class || superClass == null) {
                    break;
                }
            }
        }
    }
    if (clazz.getTypeParameters().length != 0) {
        asmEnable = false;
    }
    if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) {
        asmEnable = false;
    }
    if (asmEnable) {
        asmEnable = ASMUtils.checkName(clazz.getSimpleName());
    }
    if (asmEnable) {
        if (clazz.isInterface()) {
            asmEnable = false;
        }
        JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);
        if (asmEnable && beanInfo.fields.length > 200) {
            asmEnable = false;
        }
        Constructor<?> defaultConstructor = beanInfo.defaultConstructor;
        if (asmEnable && defaultConstructor == null && !clazz.isInterface()) {
            asmEnable = false;
        }
        for (FieldInfo fieldInfo : beanInfo.fields) {
            if (fieldInfo.getOnly) {
                asmEnable = false;
                break;
            }
            Class<?> fieldClass = fieldInfo.fieldClass;
            if (!Modifier.isPublic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }
            if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }
            if (//
            fieldInfo.getMember() != null && !ASMUtils.checkName(fieldInfo.getMember().getName())) {
                asmEnable = false;
                break;
            }
            JSONField annotation = fieldInfo.getAnnotation();
            if (//
            annotation != null && (//
            (!ASMUtils.checkName(annotation.name())) || //
            annotation.format().length() != 0 || annotation.deserializeUsing() != Void.class)) {
                asmEnable = false;
                break;
            }
            if (fieldClass.isEnum()) {
                // EnumDeserializer
                ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass);
                if (!(fieldDeser instanceof EnumDeserializer)) {
                    asmEnable = false;
                    break;
                }
            }
        }
    }
    if (asmEnable) {
        if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
            asmEnable = false;
        }
    }
    if (!asmEnable) {
        return new JavaBeanDeserializer(this, clazz, type);
    }
    JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);
    try {
        return asmFactory.createJavaBeanDeserializer(this, beanInfo);
    // } catch (VerifyError e) {
    // e.printStackTrace();
    // return new JavaBeanDeserializer(this, clazz, type);
    } catch (NoSuchMethodException ex) {
        return new JavaBeanDeserializer(this, clazz, type);
    } catch (JSONException asmError) {
        return new JavaBeanDeserializer(this, beanInfo);
    } catch (Exception e) {
        throw new JSONException("create asm deserializer error, " + clazz.getName(), e);
    }
}
Also used : JSONField(com.alibaba.fastjson.annotation.JSONField) AccessControlException(java.security.AccessControlException) JSONType(com.alibaba.fastjson.annotation.JSONType)

Example 2 with JSONField

use of com.alibaba.fastjson.annotation.JSONField in project fastjson by alibaba.

the class ParserConfig method createFieldDeserializer.

public //
FieldDeserializer createFieldDeserializer(//
ParserConfig mapping, //
JavaBeanInfo beanInfo, FieldInfo fieldInfo) {
    Class<?> clazz = beanInfo.clazz;
    Class<?> fieldClass = fieldInfo.fieldClass;
    Class<?> deserializeUsing = null;
    JSONField annotation = fieldInfo.getAnnotation();
    if (annotation != null) {
        deserializeUsing = annotation.deserializeUsing();
        if (deserializeUsing == Void.class) {
            deserializeUsing = null;
        }
    }
    if (deserializeUsing == null && (fieldClass == List.class || fieldClass == ArrayList.class)) {
        return new ArrayListTypeFieldDeserializer(mapping, clazz, fieldInfo);
    }
    return new DefaultFieldDeserializer(mapping, clazz, fieldInfo);
}
Also used : ArrayList(java.util.ArrayList) JSONField(com.alibaba.fastjson.annotation.JSONField) List(java.util.List) ArrayList(java.util.ArrayList)

Example 3 with JSONField

use of com.alibaba.fastjson.annotation.JSONField in project fastjson by alibaba.

the class JSONObject method invoke.

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length == 1) {
        if (method.getName().equals("equals")) {
            return this.equals(args[0]);
        }
        Class<?> returnType = method.getReturnType();
        if (returnType != void.class) {
            throw new JSONException("illegal setter");
        }
        String name = null;
        JSONField annotation = method.getAnnotation(JSONField.class);
        if (annotation != null) {
            if (annotation.name().length() != 0) {
                name = annotation.name();
            }
        }
        if (name == null) {
            name = method.getName();
            if (!name.startsWith("set")) {
                throw new JSONException("illegal setter");
            }
            name = name.substring(3);
            if (name.length() == 0) {
                throw new JSONException("illegal setter");
            }
            name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
        }
        map.put(name, args[0]);
        return null;
    }
    if (parameterTypes.length == 0) {
        Class<?> returnType = method.getReturnType();
        if (returnType == void.class) {
            throw new JSONException("illegal getter");
        }
        String name = null;
        JSONField annotation = method.getAnnotation(JSONField.class);
        if (annotation != null) {
            if (annotation.name().length() != 0) {
                name = annotation.name();
            }
        }
        if (name == null) {
            name = method.getName();
            if (name.startsWith("get")) {
                name = name.substring(3);
                if (name.length() == 0) {
                    throw new JSONException("illegal getter");
                }
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
            } else if (name.startsWith("is")) {
                name = name.substring(2);
                if (name.length() == 0) {
                    throw new JSONException("illegal getter");
                }
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
            } else if (name.startsWith("hashCode")) {
                return this.hashCode();
            } else if (name.startsWith("toString")) {
                return this.toString();
            } else {
                throw new JSONException("illegal getter");
            }
        }
        Object value = map.get(name);
        return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
    }
    throw new UnsupportedOperationException(method.toGenericString());
}
Also used : JSONField(com.alibaba.fastjson.annotation.JSONField)

Example 4 with JSONField

use of com.alibaba.fastjson.annotation.JSONField in project fastjson by alibaba.

the class JavaBeanInfo method build.

public static JavaBeanInfo build(Class<?> clazz, Type type, PropertyNamingStrategy propertyNamingStrategy) {
    JSONType jsonType = clazz.getAnnotation(JSONType.class);
    Class<?> builderClass = getBuilderClass(jsonType);
    Field[] declaredFields = clazz.getDeclaredFields();
    Method[] methods = clazz.getMethods();
    Constructor<?> defaultConstructor = getDefaultConstructor(builderClass == null ? clazz : builderClass);
    Constructor<?> creatorConstructor = null;
    Method buildMethod = null;
    List<FieldInfo> fieldList = new ArrayList<FieldInfo>();
    if (defaultConstructor == null && !(clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))) {
        creatorConstructor = getCreatorConstructor(clazz);
        if (creatorConstructor != null) {
            // 基于标记 JSONCreator 注解的构造方法
            TypeUtils.setAccessible(creatorConstructor);
            Class<?>[] types = creatorConstructor.getParameterTypes();
            if (types.length > 0) {
                Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations();
                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) {
                        throw new JSONException("illegal json creator");
                    }
                    Class<?> fieldClass = types[i];
                    Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
                    Field field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields);
                    final int ordinal = fieldAnnotation.ordinal();
                    final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
                    final int parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
                    FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
                    add(fieldList, fieldInfo);
                }
            }
            return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList);
        }
        // 基于标记 JSONCreator 注解的工厂方法
        Method factoryMethod = getFactoryMethod(clazz, methods);
        if (factoryMethod != null) {
            TypeUtils.setAccessible(factoryMethod);
            Class<?>[] types = factoryMethod.getParameterTypes();
            if (types.length > 0) {
                Annotation[][] paramAnnotationArrays = factoryMethod.getParameterAnnotations();
                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) {
                        throw new JSONException("illegal json creator");
                    }
                    Class<?> fieldClass = types[i];
                    Type fieldType = factoryMethod.getGenericParameterTypes()[i];
                    Field field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields);
                    final int ordinal = fieldAnnotation.ordinal();
                    final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
                    final int parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
                    FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
                    add(fieldList, fieldInfo);
                }
            }
            return new JavaBeanInfo(clazz, builderClass, null, null, factoryMethod, null, jsonType, fieldList);
        }
        throw new JSONException("default constructor not found. " + clazz);
    }
    if (defaultConstructor != null) {
        TypeUtils.setAccessible(defaultConstructor);
    }
    if (builderClass != null) {
        String withPrefix = null;
        JSONPOJOBuilder builderAnno = builderClass.getAnnotation(JSONPOJOBuilder.class);
        if (builderAnno != null) {
            withPrefix = builderAnno.withPrefix();
        }
        if (withPrefix == null || withPrefix.length() == 0) {
            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 = method.getAnnotation(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));
                    continue;
                }
            }
            String methodName = method.getName();
            if (!methodName.startsWith(withPrefix)) {
                continue;
            }
            if (methodName.length() <= withPrefix.length()) {
                continue;
            }
            char c0 = methodName.charAt(withPrefix.length());
            if (!Character.isUpperCase(c0)) {
                continue;
            }
            StringBuilder properNameBuilder = new StringBuilder(methodName.substring(withPrefix.length()));
            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));
        }
        if (builderClass != null) {
            JSONPOJOBuilder builderAnnotation = builderClass.getAnnotation(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 (methodName.length() < 4) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        // support builder set
        if (!(method.getReturnType().equals(Void.TYPE) || method.getReturnType().equals(method.getDeclaringClass()))) {
            continue;
        }
        Class<?>[] types = method.getParameterTypes();
        if (types.length != 1) {
            continue;
        }
        JSONField annotation = method.getAnnotation(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));
                continue;
            }
        }
        if (!methodName.startsWith("set")) {
            // TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解?
            continue;
        }
        char c3 = methodName.charAt(3);
        String propertyName;
        if (//
        Character.isUpperCase(c3) || // for unicode method name
        c3 > 512) {
            if (TypeUtils.compatibleWithJavaBean) {
                propertyName = TypeUtils.decapitalize(methodName.substring(3));
            } else {
                propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
            }
        } else if (c3 == '_') {
            propertyName = methodName.substring(4);
        } 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 {
            continue;
        }
        Field 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 = field.getAnnotation(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));
                    continue;
                }
            }
        }
        if (propertyNamingStrategy != null) {
            propertyName = propertyNamingStrategy.translate(propertyName);
        }
        add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null));
    }
    for (Field field : clazz.getFields()) {
        // public static fields
        int modifiers = field.getModifiers();
        if ((modifiers & Modifier.STATIC) != 0) {
            continue;
        }
        if ((modifiers & Modifier.FINAL) != 0) {
            Class<?> fieldType = field.getType();
            boolean supportReadOnly = Map.class.isAssignableFrom(fieldType) || Collection.class.isAssignableFrom(fieldType) || //
            AtomicLong.class.equals(fieldType) || //
            AtomicInteger.class.equals(fieldType) || AtomicBoolean.class.equals(fieldType);
            if (!supportReadOnly) {
                continue;
            }
        }
        boolean contains = false;
        for (FieldInfo item : fieldList) {
            if (item.name.equals(field.getName())) {
                contains = true;
                // 已经是 contains = true,无需继续遍历
                break;
            }
        }
        if (contains) {
            continue;
        }
        int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
        String propertyName = field.getName();
        JSONField fieldAnnotation = field.getAnnotation(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();
            }
        }
        if (propertyNamingStrategy != null) {
            propertyName = propertyNamingStrategy.translate(propertyName);
        }
        add(fieldList, new FieldInfo(propertyName, null, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, null, fieldAnnotation, null));
    }
    for (Method method : clazz.getMethods()) {
        // getter methods
        String methodName = method.getName();
        if (methodName.length() < 4) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (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;
                JSONField annotation = method.getAnnotation(JSONField.class);
                if (annotation != null && annotation.deserialize()) {
                    continue;
                }
                if (annotation != null && annotation.name().length() > 0) {
                    propertyName = annotation.name();
                } else {
                    propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
                }
                FieldInfo fieldInfo = getField(fieldList, propertyName);
                if (fieldInfo != null) {
                    continue;
                }
                if (propertyNamingStrategy != null) {
                    propertyName = propertyNamingStrategy.translate(propertyName);
                }
                add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, 0, 0, 0, annotation, null, null));
            }
        }
    }
    return new JavaBeanInfo(clazz, builderClass, defaultConstructor, null, null, buildMethod, jsonType, fieldList);
}
Also used : ArrayList(java.util.ArrayList) JSONPOJOBuilder(com.alibaba.fastjson.annotation.JSONPOJOBuilder) JSONField(com.alibaba.fastjson.annotation.JSONField) JSONField(com.alibaba.fastjson.annotation.JSONField) Field(java.lang.reflect.Field) JSONException(com.alibaba.fastjson.JSONException) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Type(java.lang.reflect.Type) JSONType(com.alibaba.fastjson.annotation.JSONType) AtomicLong(java.util.concurrent.atomic.AtomicLong) JSONType(com.alibaba.fastjson.annotation.JSONType)

Example 5 with JSONField

use of com.alibaba.fastjson.annotation.JSONField in project fastjson by alibaba.

the class JavaBeanSerializer method write.

public //
void write(//
JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.out;
    if (object == null) {
        out.writeNull();
        return;
    }
    if (writeReference(serializer, object, features)) {
        return;
    }
    final FieldSerializer[] getters;
    if (out.sortField) {
        getters = this.sortedGetters;
    } else {
        getters = this.getters;
    }
    SerialContext parent = serializer.context;
    serializer.setContext(parent, object, fieldName, this.beanInfo.features, features);
    final boolean writeAsArray = isWriteAsArray(serializer, features);
    try {
        final char startSeperator = writeAsArray ? '[' : '{';
        final char endSeperator = writeAsArray ? ']' : '}';
        out.append(startSeperator);
        if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
            serializer.incrementIndent();
            serializer.println();
        }
        boolean commaFlag = false;
        if ((this.beanInfo.features & SerializerFeature.WriteClassName.mask) != 0 || serializer.isWriteClassName(fieldType, object)) {
            Class<?> objClass = object.getClass();
            if (objClass != fieldType) {
                writeClassName(serializer, object);
                commaFlag = true;
            }
        }
        char seperator = commaFlag ? ',' : '\0';
        final boolean directWritePrefix = out.quoteFieldNames && !out.useSingleQuotes;
        char newSeperator = this.writeBefore(serializer, object, seperator);
        commaFlag = newSeperator == ',';
        final boolean skipTransient = out.isEnabled(SerializerFeature.SkipTransientField);
        final boolean ignoreNonFieldGetter = out.isEnabled(SerializerFeature.IgnoreNonFieldGetter);
        for (int i = 0; i < getters.length; ++i) {
            FieldSerializer fieldSerializer = getters[i];
            Field field = fieldSerializer.fieldInfo.field;
            FieldInfo fieldInfo = fieldSerializer.fieldInfo;
            String fieldInfoName = fieldInfo.name;
            Class<?> fieldClass = fieldInfo.fieldClass;
            if (skipTransient) {
                if (field != null) {
                    if (fieldInfo.fieldTransient) {
                        continue;
                    }
                }
            }
            if (ignoreNonFieldGetter) {
                if (field == null) {
                    continue;
                }
            }
            if (//
            (!this.applyName(serializer, object, fieldInfo.name)) || !this.applyLabel(serializer, fieldInfo.label)) {
                continue;
            }
            Object propertyValue;
            try {
                propertyValue = fieldSerializer.getPropertyValueDirect(object);
            } catch (InvocationTargetException ex) {
                if (out.isEnabled(SerializerFeature.IgnoreErrorGetter)) {
                    propertyValue = null;
                } else {
                    throw ex;
                }
            }
            if (!this.apply(serializer, object, fieldInfoName, propertyValue)) {
                continue;
            }
            String key = fieldInfoName;
            key = this.processKey(serializer, object, key, propertyValue);
            Object originalValue = propertyValue;
            propertyValue = this.processValue(serializer, fieldSerializer.fieldContext, object, fieldInfoName, propertyValue);
            if (propertyValue == null && !writeAsArray) {
                if ((!fieldSerializer.writeNull) && (!out.isEnabled(SerializerFeature.WRITE_MAP_NULL_FEATURES))) {
                    continue;
                }
            }
            if (propertyValue != null && out.notWriteDefaultValue) {
                Class<?> fieldCLass = fieldInfo.fieldClass;
                if (fieldCLass == byte.class && propertyValue instanceof Byte && ((Byte) propertyValue).byteValue() == 0) {
                    continue;
                } else if (fieldCLass == short.class && propertyValue instanceof Short && ((Short) propertyValue).shortValue() == 0) {
                    continue;
                } else if (fieldCLass == int.class && propertyValue instanceof Integer && ((Integer) propertyValue).intValue() == 0) {
                    continue;
                } else if (fieldCLass == long.class && propertyValue instanceof Long && ((Long) propertyValue).longValue() == 0L) {
                    continue;
                } else if (fieldCLass == float.class && propertyValue instanceof Float && ((Float) propertyValue).floatValue() == 0F) {
                    continue;
                } else if (fieldCLass == double.class && propertyValue instanceof Double && ((Double) propertyValue).doubleValue() == 0D) {
                    continue;
                } else if (fieldCLass == boolean.class && propertyValue instanceof Boolean && !((Boolean) propertyValue).booleanValue()) {
                    continue;
                }
            }
            if (commaFlag) {
                out.write(',');
                if (out.isEnabled(SerializerFeature.PrettyFormat)) {
                    serializer.println();
                }
            }
            if (key != fieldInfoName) {
                if (!writeAsArray) {
                    out.writeFieldName(key, true);
                }
                serializer.write(propertyValue);
            } else if (originalValue != propertyValue) {
                if (!writeAsArray) {
                    fieldSerializer.writePrefix(serializer);
                }
                serializer.write(propertyValue);
            } else {
                if (!writeAsArray) {
                    if (directWritePrefix) {
                        out.write(fieldInfo.name_chars, 0, fieldInfo.name_chars.length);
                    } else {
                        fieldSerializer.writePrefix(serializer);
                    }
                }
                if (!writeAsArray) {
                    JSONField fieldAnnotation = fieldInfo.getAnnotation();
                    if (fieldClass == String.class && (fieldAnnotation == null || fieldAnnotation.serializeUsing() == Void.class)) {
                        if (propertyValue == null) {
                            if ((out.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0 || (fieldSerializer.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) {
                                out.writeString("");
                            } else {
                                out.writeNull();
                            }
                        } else {
                            String propertyValueString = (String) propertyValue;
                            if (out.useSingleQuotes) {
                                out.writeStringWithSingleQuote(propertyValueString);
                            } else {
                                out.writeStringWithDoubleQuote(propertyValueString, (char) 0);
                            }
                        }
                    } else {
                        fieldSerializer.writeValue(serializer, propertyValue);
                    }
                } else {
                    fieldSerializer.writeValue(serializer, propertyValue);
                }
            }
            commaFlag = true;
        }
        this.writeAfter(serializer, object, commaFlag ? ',' : '\0');
        if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
            serializer.decrementIdent();
            serializer.println();
        }
        out.append(endSeperator);
    } catch (Exception e) {
        String errorMessage = "write javaBean error";
        if (object != null) {
            errorMessage += ", class " + object.getClass().getName();
        }
        if (fieldName != null) {
            errorMessage += ", fieldName : " + fieldName;
        }
        if (e.getMessage() != null) {
            errorMessage += (", " + e.getMessage());
        }
        throw new JSONException(errorMessage, e);
    } finally {
        serializer.context = parent;
    }
}
Also used : JSONField(com.alibaba.fastjson.annotation.JSONField) JSONException(com.alibaba.fastjson.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONException(com.alibaba.fastjson.JSONException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONField(com.alibaba.fastjson.annotation.JSONField) Field(java.lang.reflect.Field) FieldInfo(com.alibaba.fastjson.util.FieldInfo)

Aggregations

JSONField (com.alibaba.fastjson.annotation.JSONField)12 JSONException (com.alibaba.fastjson.JSONException)4 JSONType (com.alibaba.fastjson.annotation.JSONType)4 Field (java.lang.reflect.Field)4 Method (java.lang.reflect.Method)4 FieldInfo (com.alibaba.fastjson.util.FieldInfo)3 ArrayList (java.util.ArrayList)2 JSON (com.alibaba.fastjson.JSON)1 JSONObject (com.alibaba.fastjson.JSONObject)1 JSONPOJOBuilder (com.alibaba.fastjson.annotation.JSONPOJOBuilder)1 Label (com.alibaba.fastjson.asm.Label)1 ResolveTask (com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask)1 JSONLexerBase (com.alibaba.fastjson.parser.JSONLexerBase)1 ParseContext (com.alibaba.fastjson.parser.ParseContext)1 ParserConfig (com.alibaba.fastjson.parser.ParserConfig)1 IOException (java.io.IOException)1 Annotation (java.lang.annotation.Annotation)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Type (java.lang.reflect.Type)1 AccessControlException (java.security.AccessControlException)1