package cn.gtmap.estateplat.config.utils;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author <a href="mailto:lizhi@gtmap.cn">lizhi</a>
 * @version 1.0, 2018/7/24
 * @description json转换工具类
 */
public class JsonDateConvertUtil {

    /**
     *@author <a href="mailto:lizhi@gtmap.cn">lizhi</a>
     *@param beanClass 转换后的类型
     *@description json串日期类型转换
     */
    public static Object jsonDateConvert(String json, Class beanClass) {
        Object object = null;
        if (StringUtils.isNotBlank(json)) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessor() {
                @Override
                public Object processArrayValue(Object value, JsonConfig jsonConfig) {
                    String[] obj = {};
                    if (value instanceof Date[]) {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        Date[] dates = (Date[]) value;
                        obj = new String[dates.length];
                        for (int i = 0; i < dates.length; i++) {
                            obj[i] = sf.format(dates[i]);
                        }
                    }
                    return obj;
                }

                @Override
                public Object processObjectValue(String s, Object value, JsonConfig jsonConfig) {
                    if (value instanceof java.util.Date) {
                        String str = new SimpleDateFormat("yyyy-MM-dd").format((Date) value);
                        return str;
                    }
                    return value.toString();

                }
            });
            JSONObject jsonFromBean = JSONObject.fromObject(json, jsonConfig);
            String[] dateFormats = new String[]{"yyyy/MM/dd", "yyyy-MM-dd"};
            JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
            object = JSONObject.toBean(jsonFromBean, beanClass);
        }
        return object;
    }

}
