Search in sources :

Example 1 with JsonSerializable

use of com.vaadin.flow.component.JsonSerializable in project flow by vaadin.

the class JsonSerializer method toJson.

/**
 * Converts a Java bean, {@link JsonSerializable} instance, String, wrapper
 * of primitive type or enum to a {@link JsonValue}.
 * <p>
 * When a bean is used, a {@link JsonObject} is returned.
 *
 * @param bean
 *            Java object to be converted
 * @return the json representation of the Java object
 */
public static JsonValue toJson(Object bean) {
    if (bean == null) {
        return Json.createNull();
    }
    if (bean instanceof Collection) {
        return toJson((Collection<?>) bean);
    }
    if (bean.getClass().isArray()) {
        return toJsonArray(bean);
    }
    if (bean instanceof JsonSerializable) {
        return ((JsonSerializable) bean).toJson();
    }
    Optional<JsonValue> simpleType = tryToConvertToSimpleType(bean);
    if (simpleType.isPresent()) {
        return simpleType.get();
    }
    try {
        JsonObject json = Json.createObject();
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            if ("class".equals(pd.getName())) {
                continue;
            }
            Method reader = pd.getReadMethod();
            if (reader != null) {
                json.put(pd.getName(), toJson(reader.invoke(bean)));
            }
        }
        return json;
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not serialize object of type " + bean.getClass() + " to JsonValue", e);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) JsonSerializable(com.vaadin.flow.component.JsonSerializable) JsonValue(elemental.json.JsonValue) Collection(java.util.Collection) JsonObject(elemental.json.JsonObject) Method(java.lang.reflect.Method)

Example 2 with JsonSerializable

use of com.vaadin.flow.component.JsonSerializable in project flow by vaadin.

the class JsonSerializer method toObject.

@SuppressWarnings("unchecked")
private static <T> T toObject(Class<T> type, Type genericType, JsonValue json) {
    if (json == null || json instanceof JsonNull) {
        return null;
    }
    Optional<?> simpleType = tryToConvertFromSimpleType(type, json);
    if (simpleType.isPresent()) {
        return (T) simpleType.get();
    }
    if (Collection.class.isAssignableFrom(type)) {
        return toCollection(type, genericType, json);
    }
    T instance;
    try {
        instance = type.newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not create an instance of type " + type + ". Make sure it contains a default public constructor and the class is accessible.", e);
    }
    try {
        if (instance instanceof JsonSerializable && json instanceof JsonObject) {
            return type.cast(JsonSerializable.class.cast(instance).readJson((JsonObject) json));
        }
        JsonObject jsonObject = (JsonObject) json;
        String[] keys = jsonObject.keys();
        if (keys == null) {
            return instance;
        }
        BeanInfo info = Introspector.getBeanInfo(type);
        Map<String, Method> writers = new HashMap<>();
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            Method writer = pd.getWriteMethod();
            if (writer != null) {
                writers.put(pd.getName(), writer);
            }
        }
        for (String key : keys) {
            JsonValue jsonValue = jsonObject.get(key);
            Method method = writers.get(key);
            if (method != null) {
                Class<?> parameterType = method.getParameterTypes()[0];
                Type genericParameterType = method.getGenericParameterTypes()[0];
                Object value = toObject(parameterType, genericParameterType, jsonValue);
                method.invoke(instance, value);
            }
        }
        return instance;
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not deserialize object of type " + type + " from JsonValue", e);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) JsonSerializable(com.vaadin.flow.component.JsonSerializable) JsonValue(elemental.json.JsonValue) JsonObject(elemental.json.JsonObject) Method(java.lang.reflect.Method) JsonNull(elemental.json.JsonNull) JsonType(elemental.json.JsonType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) JsonObject(elemental.json.JsonObject)

Aggregations

JsonSerializable (com.vaadin.flow.component.JsonSerializable)2 JsonObject (elemental.json.JsonObject)2 JsonValue (elemental.json.JsonValue)2 BeanInfo (java.beans.BeanInfo)2 PropertyDescriptor (java.beans.PropertyDescriptor)2 Method (java.lang.reflect.Method)2 JsonNull (elemental.json.JsonNull)1 JsonType (elemental.json.JsonType)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1