关于jackson处理数据

时间:2021-02-11 22:54:57

/**
     * 将请求参数封装成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;
        }
    }