Search in sources :

Example 26 with JSONException

use of com.alibaba.fastjson.JSONException 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)

Example 27 with JSONException

use of com.alibaba.fastjson.JSONException in project fastjson by alibaba.

the class SerializeConfig method createJavaBeanSerializer.

public ObjectSerializer createJavaBeanSerializer(SerializeBeanInfo beanInfo) {
    JSONType jsonType = beanInfo.jsonType;
    if (jsonType != null) {
        Class<?> serializerClass = jsonType.serializer();
        if (serializerClass != Void.class) {
            try {
                Object seralizer = serializerClass.newInstance();
                if (seralizer instanceof ObjectSerializer) {
                    return (ObjectSerializer) seralizer;
                }
            } catch (Throwable e) {
            // skip
            }
        }
        if (jsonType.asm() == false) {
            asm = false;
        }
    }
    Class<?> clazz = beanInfo.beanType;
    if (!Modifier.isPublic(beanInfo.beanType.getModifiers())) {
        return new JavaBeanSerializer(beanInfo);
    }
    boolean asm = this.asm;
    if (asm && asmFactory.classLoader.isExternalClass(clazz) || clazz == Serializable.class || clazz == Object.class) {
        asm = false;
    }
    if (asm && !ASMUtils.checkName(clazz.getSimpleName())) {
        asm = false;
    }
    if (asm) {
        for (FieldInfo fieldInfo : beanInfo.fields) {
            Field field = fieldInfo.field;
            if (field != null && !field.getType().equals(fieldInfo.fieldClass)) {
                asm = false;
                break;
            }
            Method method = fieldInfo.method;
            if (method != null && !method.getReturnType().equals(fieldInfo.fieldClass)) {
                asm = false;
                break;
            }
            JSONField annotation = fieldInfo.getAnnotation();
            if (annotation == null) {
                continue;
            }
            if (//
            (!ASMUtils.checkName(annotation.name())) || annotation.format().length() != 0 || annotation.jsonDirect() || annotation.serializeUsing() != Void.class) {
                asm = false;
                break;
            }
            for (SerializerFeature feature : annotation.serialzeFeatures()) {
                if (SerializerFeature.WriteNonStringValueAsString == feature || SerializerFeature.WriteEnumUsingToString == feature) {
                    asm = false;
                    break;
                }
            }
        }
    }
    if (asm) {
        try {
            ObjectSerializer asmSerializer = createASMSerializer(beanInfo);
            if (asmSerializer != null) {
                return asmSerializer;
            }
        } catch (ClassFormatError e) {
        // skip
        } catch (ClassCastException e) {
        // skip
        } catch (Throwable e) {
            throw new JSONException("create asm serializer error, class " + clazz, e);
        }
    }
    return new JavaBeanSerializer(beanInfo);
}
Also used : JSONField(com.alibaba.fastjson.annotation.JSONField) JSONException(com.alibaba.fastjson.JSONException) Method(java.lang.reflect.Method) JSONField(com.alibaba.fastjson.annotation.JSONField) Field(java.lang.reflect.Field) JSONType(com.alibaba.fastjson.annotation.JSONType) FieldInfo(com.alibaba.fastjson.util.FieldInfo)

Example 28 with JSONException

use of com.alibaba.fastjson.JSONException in project fastjson by alibaba.

the class JSONSerializer method write.

public static void write(Writer out, Object object) {
    SerializeWriter writer = new SerializeWriter();
    try {
        JSONSerializer serializer = new JSONSerializer(writer);
        serializer.write(object);
        writer.writeTo(out);
    } catch (IOException ex) {
        throw new JSONException(ex.getMessage(), ex);
    } finally {
        writer.close();
    }
}
Also used : JSONException(com.alibaba.fastjson.JSONException) IOException(java.io.IOException)

Example 29 with JSONException

use of com.alibaba.fastjson.JSONException in project fastjson by alibaba.

the class AwtCodec method parseRectangle.

protected Rectangle parseRectangle(DefaultJSONParser parser) {
    JSONLexer lexer = parser.lexer;
    int x = 0, y = 0, width = 0, height = 0;
    for (; ; ) {
        if (lexer.token() == JSONToken.RBRACE) {
            lexer.nextToken();
            break;
        }
        String key;
        if (lexer.token() == JSONToken.LITERAL_STRING) {
            key = lexer.stringVal();
            lexer.nextTokenWithColon(JSONToken.LITERAL_INT);
        } else {
            throw new JSONException("syntax error");
        }
        int val;
        int token = lexer.token();
        if (token == JSONToken.LITERAL_INT) {
            val = lexer.intValue();
            lexer.nextToken();
        } else if (token == JSONToken.LITERAL_FLOAT) {
            val = (int) lexer.floatValue();
            lexer.nextToken();
        } else {
            throw new JSONException("syntax error");
        }
        if (key.equalsIgnoreCase("x")) {
            x = val;
        } else if (key.equalsIgnoreCase("y")) {
            y = val;
        } else if (key.equalsIgnoreCase("width")) {
            width = val;
        } else if (key.equalsIgnoreCase("height")) {
            height = val;
        } else {
            throw new JSONException("syntax error, " + key);
        }
        if (lexer.token() == JSONToken.COMMA) {
            lexer.nextToken(JSONToken.LITERAL_STRING);
        }
    }
    return new Rectangle(x, y, width, height);
}
Also used : Rectangle(java.awt.Rectangle) JSONException(com.alibaba.fastjson.JSONException) JSONLexer(com.alibaba.fastjson.parser.JSONLexer) Point(java.awt.Point)

Example 30 with JSONException

use of com.alibaba.fastjson.JSONException in project fastjson by alibaba.

the class AwtCodec 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;
    }
    char sep = '{';
    if (object instanceof Point) {
        Point font = (Point) object;
        sep = writeClassName(out, Point.class, sep);
        out.writeFieldValue(sep, "x", font.x);
        out.writeFieldValue(',', "y", font.y);
    } else if (object instanceof Font) {
        Font font = (Font) object;
        sep = writeClassName(out, Font.class, sep);
        out.writeFieldValue(sep, "name", font.getName());
        out.writeFieldValue(',', "style", font.getStyle());
        out.writeFieldValue(',', "size", font.getSize());
    } else if (object instanceof Rectangle) {
        Rectangle rectangle = (Rectangle) object;
        sep = writeClassName(out, Rectangle.class, sep);
        out.writeFieldValue(sep, "x", rectangle.x);
        out.writeFieldValue(',', "y", rectangle.y);
        out.writeFieldValue(',', "width", rectangle.width);
        out.writeFieldValue(',', "height", rectangle.height);
    } else if (object instanceof Color) {
        Color color = (Color) object;
        sep = writeClassName(out, Color.class, sep);
        out.writeFieldValue(sep, "r", color.getRed());
        out.writeFieldValue(',', "g", color.getGreen());
        out.writeFieldValue(',', "b", color.getBlue());
        if (color.getAlpha() > 0) {
            out.writeFieldValue(',', "alpha", color.getAlpha());
        }
    } else {
        throw new JSONException("not support awt class : " + object.getClass().getName());
    }
    out.write('}');
}
Also used : Color(java.awt.Color) Rectangle(java.awt.Rectangle) JSONException(com.alibaba.fastjson.JSONException) Point(java.awt.Point) Font(java.awt.Font)

Aggregations

JSONException (com.alibaba.fastjson.JSONException)484 JSONReader (com.alibaba.fastjson.JSONReader)83 StringReader (java.io.StringReader)83 JSONScanner (com.alibaba.fastjson.parser.JSONScanner)37 JSONObject (com.alibaba.fastjson.JSONObject)28 DefaultJSONParser (com.alibaba.fastjson.parser.DefaultJSONParser)26 Map (java.util.Map)26 JSONLexer (com.alibaba.fastjson.parser.JSONLexer)17 IOException (java.io.IOException)17 ParseException (java.text.ParseException)8 ParserConfig (com.alibaba.fastjson.parser.ParserConfig)7 FieldInfo (com.alibaba.fastjson.util.FieldInfo)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)7 JSONType (com.alibaba.fastjson.annotation.JSONType)6 JSONSerializer (com.alibaba.fastjson.serializer.JSONSerializer)6 Gson (com.google.gson.Gson)6 AccessibleObject (java.lang.reflect.AccessibleObject)6 Type (java.lang.reflect.Type)6 JSONField (com.alibaba.fastjson.annotation.JSONField)5 Point (java.awt.Point)5