com.alibaba.fastjson.util.TypeUtils Java Examples

The following examples show how to use com.alibaba.fastjson.util.TypeUtils. 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: JSONPath.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
    Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash);

    if (propertyValue == null) {
        return false;
    }

    if (propertyValue instanceof Number) {
        long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue);
        for (long value : values) {
            if (value == longPropertyValue) {
                return !not;
            }
        }
    }

    return not;
}
 
Example #2
Source File: EntityToVoMapper.java    From mPass with Apache License 2.0 6 votes vote down vote up
/** 单值数据类型转换 */
private Object castSingleValue(MapperContext context, Object srcValue,
		Class<?> targetClass) throws Exception {
	if (srcValue instanceof IEntity) {
		// 源值是Entity,拷贝一份
		Object targetValue = targetClass.newInstance();
		String entityClass = EntityUtil.getEntityClassName(srcValue);
		MetaEntity meta = MetaEntity.localEntity(entityClass);
		if (meta == null) {
			log.warn(entityClass + "的数据字典信息为空.");
		}
		MapperContext child = new MapperContext(context, meta, srcValue,
				targetValue);
		copyProperties(child);
		return targetValue;
	} else {
		// 其他,直接转
		return TypeUtils.cast(srcValue, targetClass, null);
	}
}
 
Example #3
Source File: JSONReader.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public String readString() {
    Object object;
    if (context == null) {
        object = parser.parse();
    } else {
        readBefore();
        JSONLexer lexer = parser.lexer;
        if (context.state == JSONStreamContext.StartObject && lexer.token() == JSONToken.IDENTIFIER) {
            object = lexer.stringVal();
            lexer.nextToken();
        } else {
            object = parser.parse();
        }
        readAfter();
    }

    return TypeUtils.castToString(object);
}
 
Example #4
Source File: JSONPath_s.java    From coming with MIT License 6 votes vote down vote up
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
    Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash);

    if (propertyValue == null) {
        return false;
    }

    if (propertyValue instanceof Number) {
        long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue);
        if (longPropertyValue >= startValue && longPropertyValue <= endValue) {
            return !not;
        }
    }

    return not;
}
 
Example #5
Source File: JSONPath_s.java    From coming with MIT License 6 votes vote down vote up
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
    Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash);

    if (propertyValue == null) {
        return false;
    }

    if (propertyValue instanceof Number) {
        long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue);
        for (long value : values) {
            if (value == longPropertyValue) {
                return !not;
            }
        }
    }

    return not;
}
 
Example #6
Source File: TypeReference.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private Type handlerParameterizedType(ParameterizedType type, Type[] actualTypeArguments, int actualIndex) {
    Class<?> thisClass = this.getClass();
    Type rawType = type.getRawType();
    Type[] argTypes = type.getActualTypeArguments();

    for(int i = 0; i < argTypes.length; ++i) {
        if (argTypes[i] instanceof TypeVariable && actualIndex < actualTypeArguments.length) {
            argTypes[i] = actualTypeArguments[actualIndex++];
        }

        // fix for openjdk and android env
        if (argTypes[i] instanceof GenericArrayType) {
            argTypes[i] = TypeUtils.checkPrimitiveArray(
                    (GenericArrayType) argTypes[i]);
        }

        // 如果有多层泛型且该泛型已经注明实现的情况下,判断该泛型下一层是否还有泛型
        if(argTypes[i] instanceof ParameterizedType) {
            return handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex);
        }
    }

    Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType);
    return key;
}
 
Example #7
Source File: JSONObject.java    From uavstack with Apache License 2.0 6 votes vote down vote up
static void ensureFields() {
    if (fields == null && !fields_error) {
        try {
            final Field[] declaredFields = ObjectInputStream.class.getDeclaredFields();
            String[] fieldnames = new String[]{"bin", "passHandle", "handles", "curContext"};
            Field[] array = new Field[fieldnames.length];
            for (int i = 0; i < fieldnames.length; i++) {
                Field field = TypeUtils
                        .getField(ObjectInputStream.class
                                , fieldnames[i]
                                , declaredFields
                        );
                field.setAccessible(true);
                array[i] = field;
            }
            fields = array;
        } catch (Throwable error) {
            fields_error = true;
        }
    }
}
 
Example #8
Source File: JavaBeanSerializer.java    From uavstack with Apache License 2.0 6 votes vote down vote up
protected void writeClassName(JSONSerializer serializer, String typeKey, Object object) {
    if (typeKey == null) {
        typeKey = serializer.config.typeKey;
    }
    serializer.out.writeFieldName(typeKey, false);
    String typeName = this.beanInfo.typeName;
    if (typeName == null) {
        Class<?> clazz = object.getClass();

        if (TypeUtils.isProxy(clazz)) {
            clazz = clazz.getSuperclass();
        }

        typeName = clazz.getName();
    }
    serializer.write(typeName);
}
 
Example #9
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 #10
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 #11
Source File: JSONPath_t.java    From coming with MIT License 6 votes vote down vote up
public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) {
    Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash);

    if (propertyValue == null) {
        return false;
    }

    if (propertyValue instanceof Number) {
        long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue);
        for (long value : values) {
            if (value == longPropertyValue) {
                return !not;
            }
        }
    }

    return not;
}
 
Example #12
Source File: JSONPath_s.java    From coming with MIT License 5 votes vote down vote up
public IntBetweenSegement(String propertyName, long startValue, long endValue, boolean not){
    this.propertyName = propertyName;
    this.propertyNameHash = TypeUtils.fnv1a_64(propertyName);
    this.startValue = startValue;
    this.endValue = endValue;
    this.not = not;
}
 
Example #13
Source File: ASMDeserializerFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private void _newCollection(MethodVisitor mw, Class<?> fieldClass, int i, boolean set) {
    if (fieldClass.isAssignableFrom(ArrayList.class) && !set) {
        mw.visitTypeInsn(NEW, "java/util/ArrayList");
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V");
    } else if (fieldClass.isAssignableFrom(LinkedList.class) && !set) {
        mw.visitTypeInsn(NEW, type(LinkedList.class));
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, type(LinkedList.class), "<init>", "()V");
    } else if (fieldClass.isAssignableFrom(HashSet.class)) {
        mw.visitTypeInsn(NEW, type(HashSet.class));
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, type(HashSet.class), "<init>", "()V");
    } else if (fieldClass.isAssignableFrom(TreeSet.class)) {
        mw.visitTypeInsn(NEW, type(TreeSet.class));
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, type(TreeSet.class), "<init>", "()V");
    } else if (fieldClass.isAssignableFrom(LinkedHashSet.class)) {
        mw.visitTypeInsn(NEW, type(LinkedHashSet.class));
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, type(LinkedHashSet.class), "<init>", "()V");
    } else if (set) {
        mw.visitTypeInsn(NEW, type(HashSet.class));
        mw.visitInsn(DUP);
        mw.visitMethodInsn(INVOKESPECIAL, type(HashSet.class), "<init>", "()V");
    } else {
        mw.visitVarInsn(ALOAD, 0);
        mw.visitLdcInsn(i);
        mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldType",
                           "(I)Ljava/lang/reflect/Type;");
        mw.visitMethodInsn(INVOKESTATIC, type(TypeUtils.class), "createCollection",
                           "(Ljava/lang/reflect/Type;)Ljava/util/Collection;");
    }
    mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast
}
 
Example #14
Source File: ExcelUtils.java    From poi-excel-utils with Apache License 2.0 5 votes vote down vote up
private static void setProperty(Object obj, String fieldName, Object value) throws IllegalAccessException,
                                                                           IllegalArgumentException,
                                                                           InvocationTargetException {
    PropertyDescriptor pd = getPropertyDescriptor(obj.getClass(), fieldName);
    if (pd == null || pd.getWriteMethod() == null) {
        throw new IllegalStateException("In class" + obj.getClass() + "no setter method found for field '"
                                        + fieldName + "'");
    }
    Class<?> paramType = pd.getWriteMethod().getParameterTypes()[0];
    if (value != null && !paramType.isAssignableFrom(value.getClass())) {
        value = TypeUtils.cast(value, paramType, null);
    }
    pd.getWriteMethod().invoke(obj, value);
}
 
Example #15
Source File: TypeUtil.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 转换简单类型
 */
static Object castSimple(Object value, String type) {
	Class<?> clazz = EntityUtil.TYPEMAP.get(type);
	if (clazz == null) {
		throw new ParamsNotValidException(StringHelper.join("无法转换类型:",
				value.getClass().getName(), "->", type));
	} else {
		return TypeUtils.cast(value, clazz, null);
	}
}
 
Example #16
Source File: JSONPath_s.java    From coming with MIT License 5 votes vote down vote up
public ValueSegment(String propertyName, Object value, boolean eq){
    if (value == null) {
        throw new IllegalArgumentException("value is null");
    }
    this.propertyName = propertyName;
    this.propertyNameHash = TypeUtils.fnv1a_64(propertyName);
    this.value = value;
    this.eq = eq;
}
 
Example #17
Source File: TypeUtil.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 转换枚举
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
static Object castEnum(Object value, Class<?> clazz) {
	Class<?> valueClass = ReflectUtil.getActualClass(clazz, IEnum.class,
			"V");
	Object enumValue = TypeUtils.cast(value, valueClass, null);
	return IEnum.valueOf((Class<IEnum>) clazz, enumValue);
}
 
Example #18
Source File: ResolveFieldDeserializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void setValue(Object object, Object value) {
    if (map != null) {
        map.put(key, value);
        return;
    }
    
    if (collection != null) {
        collection.add(value);
        return;
    }
    
    list.set(index, value);

    if (list instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) list;
        Object array = jsonArray.getRelatedArray();

        if (array != null) {
            int arrayLength = Array.getLength(array);

            if (arrayLength > index) {
                Object item;
                if (jsonArray.getComponentType() != null) {
                    item = TypeUtils.cast(value, jsonArray.getComponentType(), parser.getConfig());
                } else {
                    item = value;
                }
                Array.set(array, index, item);
            }
        }
    }
}
 
Example #19
Source File: TypeUtil.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 转换单值
 */
static Object castObject(Object value, Class<?> clazz) {
	if (clazz.isAssignableFrom(value.getClass())) {
		return value;
	}
	if (CURRENT.equals(value)) {
		if (Date.class.isAssignableFrom(clazz)) {
			return new Date();
		}
	}
	if (IEntity.class.isAssignableFrom(clazz)) {
		return castEntity(value, clazz);
	}
	if (IEnum.class.isAssignableFrom(clazz)) {
		return castEnum(value, clazz);
	}
	if (String.class.equals(clazz) && value instanceof IData) {
		if (value instanceof IData) {
			return ((IData) value).getFdId();
		} else if (value instanceof Map) {
			for (String key : IDKEYS) {
				Object val = ((Map<?, ?>) value).get(key);
				if (val != null && val instanceof String) {
					return (String) val;
				}
			}
		}
	}
	return TypeUtils.cast(value, clazz, null);
}
 
Example #20
Source File: JSONReader.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public Integer readInteger() {
    Object object;
    if (context == null) {
        object = parser.parse();
    } else {
        readBefore();
        object = parser.parse();
        readAfter();
    }

    return TypeUtils.castToInt(object);
}
 
Example #21
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 #22
Source File: TypeUtil.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 转换简单类型
 */
static Object castSimple(Object value, String type) {
	Class<?> clazz = EntityUtil.TYPEMAP.get(type);
	if (clazz == null) {
		throw new ParamsNotValidException(StringHelper.join("无法转换类型:",
				value.getClass().getName(), "->", type));
	} else {
		return TypeUtils.cast(value, clazz, null);
	}
}
 
Example #23
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 #24
Source File: JSONArray.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public <T> T getObject(int index, Type type) {
    Object obj = list.get(index);
    if (type instanceof Class) {
        return (T) TypeUtils.castToJavaBean(obj, (Class) type);
    } else {
        String json = JSON.toJSONString(obj);
        return (T) JSON.parseObject(json, type);
    }
}
 
Example #25
Source File: JSONPath.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public MatchSegement(
        String propertyName,
        String startsWithValue,
        String endsWithValue,
        String[] containsValues,
        boolean not)
{
    this.propertyName = propertyName;
    this.propertyNameHash = TypeUtils.fnv1a_64(propertyName);
    this.startsWithValue = startsWithValue;
    this.endsWithValue = endsWithValue;
    this.containsValues = containsValues;
    this.not = not;

    int len = 0;
    if (startsWithValue != null) {
        len += startsWithValue.length();
    }

    if (endsWithValue != null) {
        len += endsWithValue.length();
    }

    if (containsValues != null) {
        for (String item : containsValues) {
            len += item.length();
        }
    }

    this.minLength = len;
}
 
Example #26
Source File: JSONPath.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public MultiPropertySegement(String[] propertyNames){
    this.propertyNames = propertyNames;
    this.propertyNamesHash = new long[propertyNames.length];
    for (int i = 0; i < propertyNamesHash.length; i++) {
        propertyNamesHash[i] = TypeUtils.fnv1a_64(propertyNames[i]);
    }
}
 
Example #27
Source File: JSONPath.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public IntBetweenSegement(String propertyName, long startValue, long endValue, boolean not){
    this.propertyName = propertyName;
    this.propertyNameHash = TypeUtils.fnv1a_64(propertyName);
    this.startValue = startValue;
    this.endValue = endValue;
    this.not = not;
}
 
Example #28
Source File: JSONPath.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public ValueSegment(String propertyName, Object value, boolean eq){
    if (value == null) {
        throw new IllegalArgumentException("value is null");
    }
    this.propertyName = propertyName;
    this.propertyNameHash = TypeUtils.fnv1a_64(propertyName);
    this.value = value;
    this.eq = eq;
}
 
Example #29
Source File: TypeUtil.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 转换单值
 */
static Object castObject(Object value, Class<?> clazz) {
	if (clazz.isAssignableFrom(value.getClass())) {
		return value;
	}
	if (CURRENT.equals(value)) {
		if (Date.class.isAssignableFrom(clazz)) {
			return new Date();
		}
	}
	if (IEntity.class.isAssignableFrom(clazz)) {
		return castEntity(value, clazz);
	}
	if (IEnum.class.isAssignableFrom(clazz)) {
		return castEnum(value, clazz);
	}
	if (String.class.equals(clazz) && value instanceof IData) {
		if (value instanceof IData) {
			return ((IData) value).getFdId();
		} else if (value instanceof Map) {
			for (String key : IDKEYS) {
				Object val = ((Map<?, ?>) value).get(key);
				if (val != null && val instanceof String) {
					return (String) val;
				}
			}
		}
	}
	return TypeUtils.cast(value, clazz, null);
}
 
Example #30
Source File: FieldSerializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public Object getPropertyValueDirect(Object object) throws InvocationTargetException, IllegalAccessException {
    Object fieldValue =  fieldInfo.get(object);
    if (persistenceXToMany && !TypeUtils.isHibernateInitialized(fieldValue)) {
        return null;
    }
    return fieldValue;
}