com.alibaba.fastjson.parser.DefaultJSONParser Java Examples

The following examples show how to use com.alibaba.fastjson.parser.DefaultJSONParser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReferenceCodec.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    ParameterizedType paramType = (ParameterizedType) type;
    Type itemType = paramType.getActualTypeArguments()[0];

    Object itemObject = parser.parseObject(itemType);

    Type rawType = paramType.getRawType();
    if (rawType == AtomicReference.class) {
        return (T) new AtomicReference(itemObject);
    }

    if (rawType == WeakReference.class) {
        return (T) new WeakReference(itemObject);
    }

    if (rawType == SoftReference.class) {
        return (T) new SoftReference(itemObject);
    }

    throw new UnsupportedOperationException(rawType.toString());
}
 
Example #2
Source File: ReflectUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * wzy扩展
 *
 * @param input
 * @param value
 * @param config
 * @param processor
 * @param featureValues
 * @param features
 */
private static void reflectObject(String input, Object value, ParserConfig config, ParseProcess processor,
		int featureValues, Feature... features) {
	if (input == null) {
		return;
	}
	for (Feature featrue : features) {
		featureValues = Feature.config(featureValues, featrue, true);
	}

	DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);

	if (processor instanceof ExtraTypeProvider) {
		parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
	}

	if (processor instanceof ExtraProcessor) {
		parser.getExtraProcessors().add((ExtraProcessor) processor);
	}
	parser.parseObject(value);
	parser.handleResovleTask(value);
	parser.close();
}
 
Example #3
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void _createInstance(ClassWriter cw, Context context) {
    Constructor<?> defaultConstructor = context.beanInfo.defaultConstructor;
    if (!Modifier.isPublic(defaultConstructor.getModifiers())) {
        return;
    }
    
    MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "createInstance",
                                        "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;)Ljava/lang/Object;",
                                        null, null);

    mw.visitTypeInsn(NEW, type(context.getInstClass()));
    mw.visitInsn(DUP);
    mw.visitMethodInsn(INVOKESPECIAL, type(context.getInstClass()), "<init>", "()V");

    mw.visitInsn(ARETURN);
    mw.visitMaxs(3, 3);
    mw.visitEnd();
}
 
Example #4
Source File: CalendarCodec.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    Object value = DateCodec.instance.deserialze(parser, type, fieldName);

    if (value instanceof Calendar) {
        return (T) value;
    }

    Date date = (Date) value;
    if (date == null) {
        return null;
    }

    JSONLexer lexer = parser.lexer;
    Calendar calendar = Calendar.getInstance(lexer.getTimeZone(), lexer.getLocale());
    calendar.setTime(date);

    if (type == XMLGregorianCalendar.class) {
        return (T) createXMLGregorianCalendar((GregorianCalendar) calendar);
    }

    return (T) calendar;
}
 
Example #5
Source File: TestFastJson.java    From util4j with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	TestFastJson entity=new TestFastJson();
	JSONObject json=new JSONObject();
	JSONArray list=new JSONArray();
	list.add(1);
	json.put("1", 1);
	json.put("list",list);
	entity.setJson(json);
	String jsonStr=JSON.toJSONString(entity);
	System.out.println(jsonStr);
	entity=JSONObject.parseObject(jsonStr,TestFastJson.class);
	System.out.println(entity);
	//反序列化
	DefaultJSONParser jp=new DefaultJSONParser(jsonStr);
	JSONObject json2=jp.parseObject();
	System.out.println("id:"+json2.getIntValue("id"));
	//类型反序列化
	Type type=new TypeReference<TestFastJson>() {
	}.getType();
	TestFastJson entity2=JSON.parseObject(jsonStr, type);
	System.out.println(entity2.getId());
}
 
Example #6
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void _getFieldDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo) {
    Label notNull_ = new Label();
    mw.visitVarInsn(ALOAD, 0);
    mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));
    mw.visitJumpInsn(IFNONNULL, notNull_);

    mw.visitVarInsn(ALOAD, 0);

    mw.visitVarInsn(ALOAD, 1);
    mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class));
    mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass)));
    mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer",
                       "(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class));

    mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));

    mw.visitLabel(notNull_);

    mw.visitVarInsn(ALOAD, 0);
    mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));
}
 
Example #7
Source File: JSONPath_s.java    From coming with MIT License 6 votes vote down vote up
public void extract(JSONPath path, DefaultJSONParser parser, Context context) {
    if (context.eval) {
        Object object = parser.parse();
        if (object instanceof List) {
            int[] indexes = new int[this.indexes.length];
            System.arraycopy(this.indexes, 0, indexes, 0, indexes.length);
            boolean noneNegative = indexes[0] >= 0;

            List list = (List) object;
            if (noneNegative) {
                for (int i = list.size() - 1; i >= 0; i--) {
                    if (Arrays.binarySearch(indexes, i) < 0) {
                        list.remove(i);
                    }
                }
                context.object = list;
                return;
            }
        }
    }
    throw new UnsupportedOperationException();
}
 
Example #8
Source File: BigDecimalCodec.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T deserialze(DefaultJSONParser parser) {
    final JSONLexer lexer = parser.lexer;
    if (lexer.token() == JSONToken.LITERAL_INT) {
        BigDecimal decimalValue = lexer.decimalValue();
        lexer.nextToken(JSONToken.COMMA);
        return (T) decimalValue;
    }

    if (lexer.token() == JSONToken.LITERAL_FLOAT) {
        BigDecimal val = lexer.decimalValue();
        lexer.nextToken(JSONToken.COMMA);
        return (T) val;
    }

    Object value = parser.parse();
    return value == null //
        ? null //
        : (T) TypeUtils.castToBigDecimal(value);
}
 
Example #9
Source File: CollectionCodec.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    if (parser.lexer.token() == JSONToken.NULL) {
        parser.lexer.nextToken(JSONToken.COMMA);
        return null;
    }
    
    if (type == JSONArray.class) {
        JSONArray array = new JSONArray();
        parser.parseArray(array);
        return (T) array;
    }

    Collection list = TypeUtils.createCollection(type);

    Type itemType = TypeUtils.getCollectionItemType(type);
    parser.parseArray(itemType, list, fieldName);

    return (T) list;
}
 
Example #10
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void _getCollectionFieldItemDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo,
                                          Class<?> itemType) {
    Label notNull_ = new Label();
    mw.visitVarInsn(ALOAD, 0);
    mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
                      desc(ObjectDeserializer.class));
    mw.visitJumpInsn(IFNONNULL, notNull_);

    mw.visitVarInsn(ALOAD, 0);

    mw.visitVarInsn(ALOAD, 1);
    mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class));
    mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType)));
    mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer",
                       "(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class));

    mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
                      desc(ObjectDeserializer.class));

    mw.visitLabel(notNull_);
    mw.visitVarInsn(ALOAD, 0);
    mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
                      desc(ObjectDeserializer.class));
}
 
Example #11
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private void _createInstance(Context context, MethodVisitor mw) {
    JavaBeanInfo beanInfo = context.beanInfo;
    Constructor<?> defaultConstructor = beanInfo.defaultConstructor;
    if (Modifier.isPublic(defaultConstructor.getModifiers())) {
        mw.visitTypeInsn(NEW, type(context.getInstClass()));
        mw.visitInsn(DUP);

        mw.visitMethodInsn(INVOKESPECIAL, type(defaultConstructor.getDeclaringClass()), "<init>", "()V");

        mw.visitVarInsn(ASTORE, context.var("instance"));
    } else {
        mw.visitVarInsn(ALOAD, 0);
        mw.visitVarInsn(ALOAD, 1);
        mw.visitVarInsn(ALOAD, 0);
        mw.visitFieldInsn(GETFIELD, type(JavaBeanDeserializer.class), "clazz", "Ljava/lang/Class;");
        mw.visitMethodInsn(INVOKESPECIAL, type(JavaBeanDeserializer.class), "createInstance",
                           "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;)Ljava/lang/Object;");
        mw.visitTypeInsn(CHECKCAST, type(context.getInstClass())); // cast
        mw.visitVarInsn(ASTORE, context.var("instance"));
    }
}
 
Example #12
Source File: PageDeserializer.java    From phone with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked"})
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {

    	if (parser.getLexer().token() == JSONToken.NULL) {
            parser.getLexer().nextToken(JSONToken.COMMA);
            return null;
        }
        String input = parser.getInput();
//        final String inputValue = input.replaceAll("\\{.+list:\\[(.++)\\]\\}", "$1");
//        ReflectionUtil.setField(ReflectionUtil.findField(parser.getClass(), "input"), parser,inputValue );
        Page<T> list = null;
        if (null==parser.getInput()||"null".equals(input)) {
			return null;
		}
        JSONObject jo = parser.parseObject();
        JSONArray ja = jo.getJSONArray("list");
        if (ja!=null) {
            List<T> vList = (List<T>) ja;
			list = new Page<>();
			list.addAll(vList);
	        list.setTotal(jo.getIntValue("total"));
		}

        return (T) list;
    }
 
Example #13
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, int featureValues, Feature... features) {
    if (input == null) {
        return null;
    }

    for (Feature feature : features) {
        featureValues = Feature.config(featureValues, feature, true);
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues);
    T value = (T) parser.parseObject(clazz);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example #14
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(char[] input, int length, Type clazz, Feature... features) {
    if (input == null || input.length == 0) {
        return null;
    }

    int featureValues = DEFAULT_PARSER_FEATURE;
    for (Feature feature : features) {
        featureValues = Feature.config(featureValues, feature, true);
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues);
    T value = (T) parser.parseObject(clazz);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example #15
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public static JSONArray parseArray(String text) {
    if (text == null) {
        return null;
    }

    DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());

    JSONArray array;

    JSONLexer lexer = parser.lexer;
    if (lexer.token() == JSONToken.NULL) {
        lexer.nextToken();
        array = null;
    } else if (lexer.token() == JSONToken.EOF) {
        array = null;
    } else {
        array = new JSONArray();
        parser.parseArray(array);

        parser.handleResovleTask(array);
    }

    parser.close();

    return array;
}
 
Example #16
Source File: ArrayListTypeFieldDeserializer.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues) {
    JSONLexer lexer = parser.lexer;
    final int token = lexer.token();
    if (token == JSONToken.NULL
            || (token == JSONToken.LITERAL_STRING && lexer.stringVal().length() == 0)) {
        setValue(object, null);
        return;
    }

    ArrayList list = new ArrayList();

    ParseContext context = parser.getContext();

    parser.setContext(context, object, fieldInfo.name);
    parseArray(parser, objectType, list);
    parser.setContext(context);

    if (object == null) {
        fieldValues.put(fieldInfo.name, list);
    } else {
        setValue(object, list);
    }
}
 
Example #17
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public static List<Object> parseArray(String text, Type[] types) {
    if (text == null) {
        return null;
    }

    List<Object> list;

    DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
    Object[] objectArray = parser.parseArray(types);
    if (objectArray == null) {
        list = null;
    } else {
        list = Arrays.asList(objectArray);
    }

    parser.handleResovleTask(list);

    parser.close();

    return list;
}
 
Example #18
Source File: JSONPath_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @since 1.2.51
 * @param json
 * @param path
 * @return
 */
public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) {
    features |= Feature.OrderedField.mask;
    DefaultJSONParser parser = new DefaultJSONParser(json, config, features);
    JSONPath jsonPath = compile(path);
    Object result = jsonPath.extract(parser);
    parser.lexer.close();
    return result;
}
 
Example #19
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private void _setContext(Context context, MethodVisitor mw) {
    mw.visitVarInsn(ALOAD, 1); // parser
    mw.visitVarInsn(ALOAD, context.var("context"));
    mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setContext", "(" + desc(ParseContext.class) + ")V");

    Label endIf_ = new Label();
    mw.visitVarInsn(ALOAD, context.var("childContext"));
    mw.visitJumpInsn(IFNULL, endIf_);

    mw.visitVarInsn(ALOAD, context.var("childContext"));
    mw.visitVarInsn(ALOAD, context.var("instance"));
    mw.visitFieldInsn(PUTFIELD, type(ParseContext.class), "object", "Ljava/lang/Object;");

    mw.visitLabel(endIf_);
}
 
Example #20
Source File: JavaBeanDeserializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
protected Object parseRest(DefaultJSONParser parser
        , Type type
        , Object fieldName
        , Object instance
        , int features
        , int[] setFlags) {
    Object value = deserialze(parser, type, fieldName, instance, features, setFlags);

    return value;
}
 
Example #21
Source File: HunterDateDeserializer.java    From blog-hunter with MIT License 5 votes vote down vote up
@Override
public <T> T deserialze(DefaultJSONParser defaultJSONParser, Type type, Object o) {
    JSONObject object = JSONObject.parseObject(defaultJSONParser.getInput());
    if (null != o && o.equals("releaseDate")) {
        return (T) DateUtil.parse(object.get(o));
    }
    return (T) object.get(o);
}
 
Example #22
Source File: BigIntegerCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T deserialze(DefaultJSONParser parser) {
    final JSONLexer lexer = parser.lexer;
    if (lexer.token() == JSONToken.LITERAL_INT) {
        String val = lexer.numberString();
        lexer.nextToken(JSONToken.COMMA);
        return (T) new BigInteger(val);
    }

    Object value = parser.parse();
    return value == null //
        ? null //
        : (T) TypeUtils.castToBigInteger(value);
}
 
Example #23
Source File: LongCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    final JSONLexer lexer = parser.lexer;

    Long longObject;
    try {
        final int token = lexer.token();
        if (token == JSONToken.LITERAL_INT) {
            long longValue = lexer.longValue();
            lexer.nextToken(JSONToken.COMMA);
            longObject = Long.valueOf(longValue);
        } else if (token == JSONToken.LITERAL_FLOAT) {
            BigDecimal number = lexer.decimalValue();
            longObject = TypeUtils.longValue(number);
            lexer.nextToken(JSONToken.COMMA);
        } else {
            if (token == JSONToken.LBRACE) {
                JSONObject jsonObject = new JSONObject(true);
                parser.parseObject(jsonObject);
                longObject = TypeUtils.castToLong(jsonObject);
            } else {
                Object value = parser.parse();

                longObject = TypeUtils.castToLong(value);
            }
            if (longObject == null) {
                return null;
            }
        }
    } catch (Exception ex) {
        throw new JSONException("parseLong error, field : " + fieldName, ex);
    }
    
    return clazz == AtomicLong.class //
        ? (T) new AtomicLong(longObject.longValue()) //
        : (T) longObject;
}
 
Example #24
Source File: AwtCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")

    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        JSONLexer lexer = parser.lexer;

        if (lexer.token() == JSONToken.NULL) {
            lexer.nextToken(JSONToken.COMMA);
            return null;
        }

        if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
            throw new JSONException("syntax error");
        }
        lexer.nextToken();

        T obj;
        if (type == Point.class) {
            obj = (T) parsePoint(parser, fieldName);
        } else if (type == Rectangle.class) {
            obj = (T) parseRectangle(parser);
        } else if (type == Color.class) {
            obj = (T) parseColor(parser);
        } else if (type == Font.class) {
            obj = (T) parseFont(parser);
        } else {
            throw new JSONException("not support awt class : " + type);
        }

        ParseContext context = parser.getContext();
        parser.setContext(obj, fieldName);
        parser.setContext(context);

        return obj;
    }
 
Example #25
Source File: AwtCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private Object parseRef(DefaultJSONParser parser, Object fieldName) {
    JSONLexer lexer = parser.getLexer();
    lexer.nextTokenWithColon(JSONToken.LITERAL_STRING);
    String ref = lexer.stringVal();
    parser.setContext(parser.getContext(), fieldName);
    parser.addResolveTask(new DefaultJSONParser.ResolveTask(parser.getContext(), ref));
    parser.popContext();
    parser.setResolveStatus(DefaultJSONParser.NeedToResolve);
    lexer.nextToken(JSONToken.RBRACE);
    parser.accept(JSONToken.RBRACE);
    return null;
}
 
Example #26
Source File: CharacterCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    Object value = parser.parse();
    return value == null //
        ? null //
        : (T) TypeUtils.castToChar(value);
}
 
Example #27
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @since 1.2.38
 */
public static Object parse(String text, ParserConfig config, int features) {
    if (text == null) {
        return null;
    }

    DefaultJSONParser parser = new DefaultJSONParser(text, config, features);
    Object value = parser.parse();

    parser.handleResovleTask(value);

    parser.close();

    return value;
}
 
Example #28
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor,
                                      int featureValues, Feature... features) {
    if (input == null) {
        return null;
    }

    if (features != null) {
        for (Feature feature : features) {
            featureValues |= feature.mask;
        }
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);

    if (processor != null) {
        if (processor instanceof ExtraTypeProvider) {
            parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
        }

        if (processor instanceof ExtraProcessor) {
            parser.getExtraProcessors().add((ExtraProcessor) processor);
        }

        if (processor instanceof FieldTypeResolver) {
            parser.setFieldTypeResolver((FieldTypeResolver) processor);
        }
    }

    T value = (T) parser.parseObject(clazz, null);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example #29
Source File: FastJsonSObjectCodec.java    From actframework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.LITERAL_STRING) {
        String text = lexer.stringVal();
        lexer.nextToken(JSONToken.COMMA);
        return (T) resolver.resolve(text);
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example #30
Source File: JSONPath_s.java    From coming with MIT License 5 votes vote down vote up
public void extract(JSONPath path, DefaultJSONParser parser, Context context) {
    JSONLexerBase lexer = (JSONLexerBase) parser.lexer;
    if (lexer.seekArrayToItem(index)
            && context.eval)
    {
        context.object = parser.parse();
    }
}