All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.aidensuen.mongo.support.MapToObjectConverter Maven / Gradle / Ivy

There is a newer version: 1.1.2
Show newest version
package com.github.aidensuen.mongo.support;

import com.github.aidensuen.util.BeanWrapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MapToObjectConverter implements ConditionalGenericConverter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MapToObjectConverter.class);

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return Map.class.isAssignableFrom(sourceType.getObjectType());
    }

    @Override
    public Set getConvertibleTypes() {
        Set convertiblePairs = new HashSet<>();
        convertiblePairs.add(new ConvertiblePair(Map.class, Object.class));
        return convertiblePairs;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        try {
            Object target = targetType.getObjectType().newInstance();
            BeanWrapper beanWrapper = BeanWrapperUtil.initBeanWrapper(target);
            beanWrapper.setPropertyValues((Map) source);
            return target;
        } catch (Exception e) {
            LOGGER.error(e.toString());
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy