Search in sources :

Example 21 with ObjectDeserializer

use of com.alibaba.fastjson.parser.deserializer.ObjectDeserializer in project fastjson by alibaba.

the class TypeUtils method cast.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T cast(final Object obj, final Class<T> clazz, ParserConfig config) {
    if (obj == null) {
        if (clazz == int.class) {
            return (T) Integer.valueOf(0);
        } else if (clazz == long.class) {
            return (T) Long.valueOf(0);
        } else if (clazz == short.class) {
            return (T) Short.valueOf((short) 0);
        } else if (clazz == byte.class) {
            return (T) Byte.valueOf((byte) 0);
        } else if (clazz == float.class) {
            return (T) Float.valueOf(0);
        } else if (clazz == double.class) {
            return (T) Double.valueOf(0);
        } else if (clazz == boolean.class) {
            return (T) Boolean.FALSE;
        }
        return null;
    }
    if (clazz == null) {
        throw new IllegalArgumentException("clazz is null");
    }
    if (clazz == obj.getClass()) {
        return (T) obj;
    }
    if (obj instanceof Map) {
        if (clazz == Map.class) {
            return (T) obj;
        }
        Map map = (Map) obj;
        if (clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)) {
            return (T) obj;
        }
        return castToJavaBean((Map<String, Object>) obj, clazz, config);
    }
    if (clazz.isArray()) {
        if (obj instanceof Collection) {
            Collection collection = (Collection) obj;
            int index = 0;
            Object array = Array.newInstance(clazz.getComponentType(), collection.size());
            for (Object item : collection) {
                Object value = cast(item, clazz.getComponentType(), config);
                Array.set(array, index, value);
                index++;
            }
            return (T) array;
        }
        if (clazz == byte[].class) {
            return (T) castToBytes(obj);
        }
    }
    if (clazz.isAssignableFrom(obj.getClass())) {
        return (T) obj;
    }
    if (clazz == boolean.class || clazz == Boolean.class) {
        return (T) castToBoolean(obj);
    }
    if (clazz == byte.class || clazz == Byte.class) {
        return (T) castToByte(obj);
    }
    if (clazz == char.class || clazz == Character.class) {
        return (T) castToChar(obj);
    }
    if (clazz == short.class || clazz == Short.class) {
        return (T) castToShort(obj);
    }
    if (clazz == int.class || clazz == Integer.class) {
        return (T) castToInt(obj);
    }
    if (clazz == long.class || clazz == Long.class) {
        return (T) castToLong(obj);
    }
    if (clazz == float.class || clazz == Float.class) {
        return (T) castToFloat(obj);
    }
    if (clazz == double.class || clazz == Double.class) {
        return (T) castToDouble(obj);
    }
    if (clazz == String.class) {
        return (T) castToString(obj);
    }
    if (clazz == BigDecimal.class) {
        return (T) castToBigDecimal(obj);
    }
    if (clazz == BigInteger.class) {
        return (T) castToBigInteger(obj);
    }
    if (clazz == Date.class) {
        return (T) castToDate(obj);
    }
    T retObj = (T) ModuleUtil.callWhenHasJavaSql(castFunction, obj, clazz);
    if (retObj != null) {
        return retObj;
    }
    if (clazz.isEnum()) {
        return castToEnum(obj, clazz, config);
    }
    if (Calendar.class.isAssignableFrom(clazz)) {
        Date date = castToDate(obj);
        Calendar calendar;
        if (clazz == Calendar.class) {
            calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
        } else {
            try {
                calendar = (Calendar) clazz.newInstance();
            } catch (Exception e) {
                throw new JSONException("can not cast to : " + clazz.getName(), e);
            }
        }
        calendar.setTime(date);
        return (T) calendar;
    }
    String className = clazz.getName();
    if (className.equals("javax.xml.datatype.XMLGregorianCalendar")) {
        Date date = castToDate(obj);
        Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
        calendar.setTime(date);
        return (T) CalendarCodec.instance.createXMLGregorianCalendar(calendar);
    }
    if (obj instanceof String) {
        String strVal = (String) obj;
        if (// 
        strVal.length() == 0 || // 
        "null".equals(strVal) || "NULL".equals(strVal)) {
            return null;
        }
        if (clazz == java.util.Currency.class) {
            return (T) java.util.Currency.getInstance(strVal);
        }
        if (clazz == java.util.Locale.class) {
            return (T) toLocale(strVal);
        }
        if (className.startsWith("java.time.")) {
            String json = JSON.toJSONString(strVal);
            return JSON.parseObject(json, clazz);
        }
    }
    final ObjectDeserializer objectDeserializer = config.get(clazz);
    if (objectDeserializer != null) {
        String str = JSON.toJSONString(obj);
        return JSON.parseObject(str, clazz);
    }
    throw new JSONException("can not cast to : " + clazz.getName());
}
Also used : JSONException(com.alibaba.fastjson.JSONException) ParseException(java.text.ParseException) JSONException(com.alibaba.fastjson.JSONException) AccessControlException(java.security.AccessControlException) BigInteger(java.math.BigInteger) java.util(java.util) JSONObject(com.alibaba.fastjson.JSONObject) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ObjectDeserializer(com.alibaba.fastjson.parser.deserializer.ObjectDeserializer)

Example 22 with ObjectDeserializer

use of com.alibaba.fastjson.parser.deserializer.ObjectDeserializer in project fastjson by alibaba.

the class TypeUtils method cast.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T cast(Object obj, ParameterizedType type, ParserConfig mapping) {
    Type rawTye = type.getRawType();
    if (rawTye == List.class || rawTye == ArrayList.class) {
        Type itemType = type.getActualTypeArguments()[0];
        if (obj instanceof List) {
            List listObj = (List) obj;
            List arrayList = new ArrayList(listObj.size());
            for (Object item : listObj) {
                Object itemValue;
                if (itemType instanceof Class) {
                    if (item != null && item.getClass() == JSONObject.class) {
                        itemValue = ((JSONObject) item).toJavaObject((Class<T>) itemType, mapping, 0);
                    } else {
                        itemValue = cast(item, (Class<T>) itemType, mapping);
                    }
                } else {
                    itemValue = cast(item, itemType, mapping);
                }
                arrayList.add(itemValue);
            }
            return (T) arrayList;
        }
    }
    if (// 
    rawTye == Set.class || rawTye == HashSet.class || // 
    rawTye == TreeSet.class || // 
    rawTye == Collection.class || // 
    rawTye == List.class || rawTye == ArrayList.class) {
        Type itemType = type.getActualTypeArguments()[0];
        if (obj instanceof Iterable) {
            Collection collection;
            if (rawTye == Set.class || rawTye == HashSet.class) {
                collection = new HashSet();
            } else if (rawTye == TreeSet.class) {
                collection = new TreeSet();
            } else {
                collection = new ArrayList();
            }
            for (Object item : (Iterable) obj) {
                Object itemValue;
                if (itemType instanceof Class) {
                    if (item != null && item.getClass() == JSONObject.class) {
                        itemValue = ((JSONObject) item).toJavaObject((Class<T>) itemType, mapping, 0);
                    } else {
                        itemValue = cast(item, (Class<T>) itemType, mapping);
                    }
                } else {
                    itemValue = cast(item, itemType, mapping);
                }
                collection.add(itemValue);
            }
            return (T) collection;
        }
    }
    if (rawTye == Map.class || rawTye == HashMap.class) {
        Type keyType = type.getActualTypeArguments()[0];
        Type valueType = type.getActualTypeArguments()[1];
        if (obj instanceof Map) {
            Map map = new HashMap();
            for (Map.Entry entry : ((Map<?, ?>) obj).entrySet()) {
                Object key = cast(entry.getKey(), keyType, mapping);
                Object value = cast(entry.getValue(), valueType, mapping);
                map.put(key, value);
            }
            return (T) map;
        }
    }
    if (obj instanceof String) {
        String strVal = (String) obj;
        if (strVal.length() == 0) {
            return null;
        }
    }
    Type[] actualTypeArguments = type.getActualTypeArguments();
    if (actualTypeArguments.length == 1) {
        Type argType = type.getActualTypeArguments()[0];
        if (argType instanceof WildcardType) {
            return (T) cast(obj, rawTye, mapping);
        }
    }
    if (rawTye == Map.Entry.class && obj instanceof Map && ((Map) obj).size() == 1) {
        Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next();
        Object entryValue = entry.getValue();
        if (actualTypeArguments.length == 2 && entryValue instanceof Map) {
            Type valueType = actualTypeArguments[1];
            entry.setValue(cast(entryValue, valueType, mapping));
        }
        return (T) entry;
    }
    if (rawTye instanceof Class) {
        if (mapping == null) {
            mapping = ParserConfig.global;
        }
        ObjectDeserializer deserializer = mapping.getDeserializer(rawTye);
        if (deserializer != null) {
            String str = JSON.toJSONString(obj);
            DefaultJSONParser parser = new DefaultJSONParser(str, mapping);
            return (T) deserializer.deserialze(parser, type, null);
        }
    }
    throw new JSONException("can not cast to : " + type);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JSONException(com.alibaba.fastjson.JSONException) JSONType(com.alibaba.fastjson.annotation.JSONType) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject) DefaultJSONParser(com.alibaba.fastjson.parser.DefaultJSONParser) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ObjectDeserializer(com.alibaba.fastjson.parser.deserializer.ObjectDeserializer)

Example 23 with ObjectDeserializer

use of com.alibaba.fastjson.parser.deserializer.ObjectDeserializer in project fastjson by alibaba.

the class Bug_for_issue_372 method test_for_issue.

public void test_for_issue() throws Exception {
    ParserConfig config = new ParserConfig();
    ObjectDeserializer deser = config.getDeserializer(Model.class);
    Assert.assertEquals(JavaBeanDeserializer.class, deser.getClass());
}
Also used : ParserConfig(com.alibaba.fastjson.parser.ParserConfig) ObjectDeserializer(com.alibaba.fastjson.parser.deserializer.ObjectDeserializer)

Example 24 with ObjectDeserializer

use of com.alibaba.fastjson.parser.deserializer.ObjectDeserializer in project fastjson by alibaba.

the class AEHuangliang2Test method test_for_issue.

public void test_for_issue() throws Exception {
    ParserConfig.getGlobalInstance().putDeserializer(Area.class, new ObjectDeserializer() {

        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            JSONObject jsonObject = (JSONObject) parser.parse();
            String areaType;
            if (jsonObject.get("type") instanceof String) {
                areaType = (String) jsonObject.get("type");
            } else {
                return null;
            }
            if (Area.TYPE_SECTION.equals(areaType)) {
                String text = jsonObject.toJSONString();
                return (T) JSON.parseObject(text, Section.class);
            } else if (Area.TYPE_FLOORV1.equals(areaType)) {
                String text = jsonObject.toJSONString();
                return (T) JSON.parseObject(text, FloorV1.class);
            } else if (Area.TYPE_FLOORV2.equals(areaType)) {
                String text = jsonObject.toJSONString();
                return (T) JSON.parseObject(text, FloorV2.class);
            }
            return null;
        }

        public int getFastMatchToken() {
            return JSONToken.LBRACE;
        }
    });
    ParserConfig.getGlobalInstance().addAccept("section");
    ParserConfig.getGlobalInstance().addAccept("floorV2");
    MockResult data = JSON.parseObject(floordata, MockResult.class);
    String mockResultJson = JSON.toJSONString(data.mockResult);
    NetResponse response = JSON.parseObject(mockResultJson, NetResponse.class);
    String bodyJson = JSON.toJSONString(response.body);
    System.out.println(bodyJson);
    FloorPageData pageData = JSON.parseObject(bodyJson, FloorPageData.class);
    assertNotNull(pageData.areas);
}
Also used : Type(java.lang.reflect.Type) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject) DefaultJSONParser(com.alibaba.fastjson.parser.DefaultJSONParser) ObjectDeserializer(com.alibaba.fastjson.parser.deserializer.ObjectDeserializer)

Example 25 with ObjectDeserializer

use of com.alibaba.fastjson.parser.deserializer.ObjectDeserializer in project fastjson by alibaba.

the class JSONFieldTest_1 method test_0.

public void test_0() throws Exception {
    VO vo = new VO();
    vo.setF0(100);
    vo.setF1(101);
    vo.setF2(102);
    String text = JSON.toJSONString(vo);
    System.out.println(text);
    Assert.assertEquals("{\"f2\":102,\"f1\":101,\"f0\":100}", text);
    VO vo_decoded = JSON.parseObject(text, VO.class);
    Assert.assertEquals(vo.f0, vo_decoded.f0);
    Assert.assertEquals(vo.f1, vo_decoded.f1);
    Assert.assertEquals(vo.f2, vo_decoded.f2);
    JavaBeanDeserializer javaBeanDeser = null;
    ObjectDeserializer deser = ParserConfig.getGlobalInstance().getDeserializer(VO.class);
    javaBeanDeser = (JavaBeanDeserializer) deser;
    Field field = JavaBeanDeserializer.class.getDeclaredField("sortedFieldDeserializers");
    field.setAccessible(true);
    FieldDeserializer[] fieldDeserList = (FieldDeserializer[]) field.get(javaBeanDeser);
    Assert.assertEquals(3, fieldDeserList.length);
    Assert.assertEquals("f2", fieldDeserList[0].fieldInfo.name);
    Assert.assertEquals("f1", fieldDeserList[1].fieldInfo.name);
    Assert.assertEquals("f0", fieldDeserList[2].fieldInfo.name);
}
Also used : FieldDeserializer(com.alibaba.fastjson.parser.deserializer.FieldDeserializer) JSONField(com.alibaba.fastjson.annotation.JSONField) Field(java.lang.reflect.Field) ObjectDeserializer(com.alibaba.fastjson.parser.deserializer.ObjectDeserializer) JavaBeanDeserializer(com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer)

Aggregations

ObjectDeserializer (com.alibaba.fastjson.parser.deserializer.ObjectDeserializer)27 JSONObject (com.alibaba.fastjson.JSONObject)12 JSONException (com.alibaba.fastjson.JSONException)10 JavaBeanDeserializer (com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer)10 Type (java.lang.reflect.Type)9 FieldDeserializer (com.alibaba.fastjson.parser.deserializer.FieldDeserializer)8 HashMap (java.util.HashMap)7 Map (java.util.Map)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)7 ConcurrentMap (java.util.concurrent.ConcurrentMap)7 DefaultJSONParser (com.alibaba.fastjson.parser.DefaultJSONParser)5 ParameterizedType (java.lang.reflect.ParameterizedType)4 WildcardType (java.lang.reflect.WildcardType)4 BigInteger (java.math.BigInteger)4 AccessControlException (java.security.AccessControlException)4 ArrayList (java.util.ArrayList)4 IdentityHashMap (java.util.IdentityHashMap)4 ParserConfig (com.alibaba.fastjson.parser.ParserConfig)3 ParseException (java.text.ParseException)3 List (java.util.List)3