/**
     * 将请求参数封装成Map对象
     *
     * @param json 参数
     * @return Object
     */
    public static Map wrapMap(String json) {
        if (json == null) return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.getDeserializationConfig().setDateFormat(new DateFormat());
        try {
            return mapper.readValue(json, TypeFactory.mapType(HashMap.class, String.class, Object.class));
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

/**
     * 将请求参数map封装成Bean对象
     *
     * @param request 请求对象
     * @param cls     类class
     * @return Object
     */
    public static <T> T wrapBean(Class<T> cls, HttpServletRequest request) {
        try {
            T obj = cls.newInstance();
            if (obj instanceof Map) {
                BeanUtils.populate(obj, request.getParameterMap());
            } else {
                setBeanProperty(obj, request.getParameterMap());
            }
            return obj;
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

/**
     * 将请求参数的parameterMap设置到bean对象的属性中
     *
     * @param obj bean对象
     * @param map request.getParameterMap()
     */
    private static void setBeanProperty(Object obj, Map map) {
        if (map == null) return;
        for (Object o : map.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();

String[] values = null;
            String value = null;
            Object object = entry.getValue();
            if (object != null) {
                if (object.getClass() == String[].class) {
                    values = (String[]) object;
                    value = values[0];
                } else if (object.getClass() == String.class) {
                    values = new String[]{(String) object};
                    value = (String) object;
                }
            }

//String[] values = (String[]) entry.getValue();
            if (!PropertyUtils.isWriteable(obj, key)) continue;
            try {
                Class cls = PropertyUtils.getPropertyType(obj, key);
                if (cls == null) continue;
                //String value = (values != null && values.length > 0) ? values[0] : null;
                if (cls == String.class) PropertyUtils.setProperty(obj, key, value);
                else if (cls == String[].class) PropertyUtils.setProperty(obj, key, values);
                else if (cls == BigDecimal.class) PropertyUtils.setProperty(obj, key, BeanUtil.toBigDecimal(value));
                else if (cls == BigDecimal[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toBigDecimal(values));
                else if (cls == BigInteger.class) PropertyUtils.setProperty(obj, key, BeanUtil.toBigInteger(value));
                else if (cls == BigInteger[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toBigInteger(values));
                else if (cls == Boolean.class) PropertyUtils.setProperty(obj, key, BeanUtil.toBoolean(value));
                else if (cls == Boolean[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toBoolean(values));
                else if (cls == Double.class) PropertyUtils.setProperty(obj, key, BeanUtil.toDouble(value));
                else if (cls == Double[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toDouble(values));
                else if (cls == Float.class) PropertyUtils.setProperty(obj, key, BeanUtil.toFloat(value));
                else if (cls == Float[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toFloat(values));
                else if (cls == Integer.class) PropertyUtils.setProperty(obj, key, BeanUtil.toInteger(value));
                else if (cls == Integer[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toInteger(values));
                else if (cls == Long.class) PropertyUtils.setProperty(obj, key, BeanUtil.toLong(value));
                else if (cls == Long[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toLong(values));
                else if (cls == Short.class) PropertyUtils.setProperty(obj, key, BeanUtil.toShort(value));
                else if (cls == Short[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toShort(values));
                else if (cls == Byte.class) PropertyUtils.setProperty(obj, key, BeanUtil.toByte(value));
                else if (cls == Byte[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toByte(values));
                else if (cls == Date.class) PropertyUtils.setProperty(obj, key, BeanUtil.toDate(value));
                else if (cls == Date[].class) PropertyUtils.setProperty(obj, key, BeanUtil.toDate(values));
            } catch (Exception e) {
                logger.error(getExceptionMessage(e));
            }
        }
    }

/**
     * 设置对象的属性
     *
     * @param obj
     * @param field
     * @param value
     */
    public static void setProperty(Object obj, Field field, String value) {
        try {
            if (field.getType() == String.class) PropertyUtils.setProperty(obj, field.getName(), value);
            else if (field.getType() == BigDecimal.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toBigDecimal(value));
            else if (field.getType() == BigInteger.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toBigInteger(value));
            else if (field.getType() == Boolean.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toBoolean(value));
            else if (field.getType() == Double.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toDouble(value));
            else if (field.getType() == Float.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toFloat(value));
            else if (field.getType() == Integer.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toInteger(value));
            else if (field.getType() == Long.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toLong(value));
            else if (field.getType() == Short.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toShort(value));
            else if (field.getType() == Byte.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toByte(value));
            else if (field.getType() == Date.class)
                PropertyUtils.setProperty(obj, field.getName(), BeanUtil.toDate(value));
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
        }
    }

/**
     * 将以json方式提交的字符串封装成Bean对象
     *
     * @param json json对象
     * @param cls  bean的class
     * @return Object
     */
    public static <T> T wrapBean(Class<T> cls, String json) {
        if (json == null) return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.getDeserializationConfig().setDateFormat(new DateFormat());
        try {
            return mapper.readValue(json, cls);
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

/**
     * 将以json方式提交的字符串封装成Bean对象
     *
     * @param json     json对象
     * @param javaType bean的class
     * @return Object
     */
    @SuppressWarnings({"unchecked"})
    public static <T> T wrapBean(JavaType javaType, String json) {
        if (json == null) return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.getDeserializationConfig().setDateFormat(new DateFormat());
        try {
            return (T) mapper.readValue(json, javaType);
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

/**
     * 将json 数组封装成 arrays
     *
     * @param json json数组
     * @param cls  类名
     * @return T[]
     */
    @SuppressWarnings({"unchecked"})
    public static <T> T wrapArray(Class cls, String json) {
        if (json == null) return null;
        return (T) wrapBean(TypeFactory.arrayType(cls), json);
    }

/**
     * 将以json方式提交的字符串封装成Bean集合
     *
     * @param jsonArray json数组
     * @param cls       bean的class
     * @return List
     */
    public static <T> List<T> wrapBeanList(Class<T> cls, String jsonArray) {
        if (jsonArray == null) return null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.getDeserializationConfig().setDateFormat(new DateFormat());
        try {
            return mapper.readValue(jsonArray, TypeFactory.collectionType(List.class, cls));
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

/**
     * 对象转换json字符串
     *
     * @param obj 对象
     * @return String
     */
    public static String toJsonString(Object obj) {
        if (obj == null) return null;
        ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        mapper.getSerializationConfig().disable(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES);
        mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
//        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//为true表示允许单引号
//        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);//为true表示允许无引号包括的字段
//        mapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.getSerializationConfig().setDateFormat(new DateFormat("yyyy-MM-dd HH:mm:ss"));
        CustomSerializerFactory sf = new CustomSerializerFactory();
//        sf.addSpecificMapping(Long.class, new LongSerializer());
//        sf.addSpecificMapping(Double.class,new DoubleSerializer());
        sf.addSpecificMapping(TIMESTAMP.class, new TimeStampSerializer());
        mapper.setSerializerFactory(sf);
        try {
            StringWriter sb = new StringWriter();
            mapper.writeValue(sb, obj);
            return sb.toString();
        } catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

关于jackson处理数据的更多相关文章

  1. 利用Jackson将数据转换为Json

    1.确保相关依赖导入 2.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app ...

  2. sun.jersey使用Jackson转换数据

    差点被com.sun.jersey自身的json转换吓死,遇到List等类型,会把这些也转换为json对象,而不是jsonarray. 被园里的同行拯救了,在web.xml中配置一下就ok. < ...

  3. JSON解析器之jackson json数据和java对象转换

  4. 利用Jackson序列化实现数据脱敏

    几天前使用了Jackson对数据的自定义序列化.突发灵感,利用此方法来简单实现接口返回数据脱敏,故写此文记录. 核心思想是利用Jackson的StdSerializer,@JsonSerialize, ...

  5. com.fasterxml.jackson.databind.JsonMappingException

    背景 在搭建SSM整合activiti项目时,在查找activiti定义的流程模板时,前台不能够接受到ProcessDefinition这个对象. 原因 ProcessDefinition是一个接口, ...

  6. SpringBoot前后端分离Instant时间戳自定义解析

    在SpringBoot项目中,前后端规定传递时间使用时间戳(精度ms). @Data public class Incident { @ApiModelProperty(value = "故 ...

  7. spring boot中的约定优于配置

    Spring Boot并不是一个全新的框架,而是将已有的Spring组件整合起来. Spring Boot可以说是遵循约定优于配置这个理念产生的.它的特点是简单.快速和便捷. 既然遵循约定优于配置,则 ...

  8. Spring Boot基础讲解

    Spring Boot Spring Boot 是由Pivotal团队提供的框架,它并不是一个全新的框架,而是将已有的 Spring 组件整合起来,设计目的是用来简化新Spring应用的初始搭建以及开 ...

  9. Oracle 基于用户管理恢复的处理

    ================================ -- Oracle 基于用户管理恢复的处理 --================================ Oracle支持多种 ...

随机推荐

  1. JavaScript 面向对象(三) —— 高级篇

    JavaScript 面向对象(一) —— 基础篇 JavaScript 面向对象(二) —— 案例篇 一.json方式的面向对象 首先要知道,js中出现的东西都能够放到json中.关于json数据格 ...

  2. [原创]C#应用WindowsApi实现查找(FindWindowEx)文本框(TextBox、TextEdit)。

    /// <summary> /// 获取文本框控件 /// </summary> /// <param name="hwnd">文本框所在父窗口 ...

  3. 四步完成NodeJS安装,配置和测试

    四步完成NodeJS安装,配置和测试 NodeJS 官网地址: http://nodejs.org/ 第一步:在官网点击 ’ INSTALL ’,下载相应的版本(我的机器是Win7专业版 64bit) ...

  4. 【资讯】天啦鲁,这十余款创客设计居然由FPGA搞定 [转]

    按理说‘高大上’的FPGA,多出现在航天航空(如火星探测器).通信(如基站.数据中心).测试测量等高端应用场景.但麦迪却也发现,近期,在很多创客的作品内部都有FPGA的影子.这或许也从侧面看出,打从总 ...

  5. Win8 传统桌面下无法上网的解决方法

    Win8 很酷,就连出现的问题也都酷得不行~ 之前遇到的一些问题与解决方法,避免重新安装 1. Word 2013下, 输入法突然秀逗, 经常按了一个键后, 死循环输入该字符直到死机 解决方法: 进入 ...

  6. HalconMFC(一)之多版本配置

    今天比较匆忙,还得写周六日考试扯P的PPT,就先这样开个头吧.我的电脑是win7,32位的系统,我用Halcon10.0.但是很多小伙伴的都是64位系统的,所以我用小伙伴的64位系统试过很多次用VC配 ...

  7. Hadoop的数据输入的源码解析

    我们知道,任何一个工程项目,最重要的是三个部分:输入,中间处理,输出.今天我们来深入的了解一下我们熟知的Hadoop系统中,输入是如何输入的? 在hadoop中,输入数据都是通过对应的InputFor ...

  8. 自定义iOS7导航栏背景,标题和返回按钮文字颜色

    在iOS7下,默认导航栏背景,颜色是这样的,接下来我们就进行自定义,如果你仅仅是更改一下背景和颜色,代码会很简单,不需要很复杂的自定义View来替代leftBarItem 更改导航栏的背景和文字Col ...

  9. 关于用Java实现二维码的生成

    昨天晚上看了一个视频讲的是web端把名片搞成二维码的形式,觉得挺有意思的,不过我还是初学,所以就没在网页端实现,写了命令行程序. 虽然看着程序很短,不过写的过程中还是出了问题, 最致命的就是 Grap ...

  10. STM32系列单片机IO口模式设置

    STM32单片机的每组IO口都有4个32位配置寄存器用于配置GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR和GPIOx_PUPDR,2个32位数据寄存器用于配置输入和 ...