Json   发布时间:2022-04-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了JsonUtils & json转换大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

package com.ynet.ci.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.math.bigdecimal;
import java.math.bigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Helpers.FormatTingTuple;
import org.slf4j.Helpers.messageformatter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.Jsonserializer;
import com.fasterxml.jackson.databind.objectMapper;
import com.fasterxml.jackson.databind.serializationFeature;
import com.fasterxml.jackson.databind.serializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
* JSON 转换相关的工具类 注意,Map的Key只能为简单类型,不可采用复杂类型.
* @author moping
*/

@SuppressWarnings(“unchecked”)
public final class JsonUtils {

private static final TypeFactory TYPE_FACTORY = TypeFactory.defaulTinstance();
private static final long LONG_JS_MAX_VLAUE = 1L << 53;
private static final Pattern numbER_PATTERN = Pattern.compile("^\\d*$");
private static final Pattern DATE_1_PATTERN = Pattern.compile("^19\\d{12}$");
private static final Pattern DATE_2_PATTERN = Pattern.compile("^20\\d{12}$");
private static final Pattern DATE_3_PATTERN = Pattern.compile("^\\d{4}[-]\\d{2}$");
private static final Pattern DATE_4_PATTERN = Pattern.compile("^\\d{4}[-]\\d{2}[-]\\d{2}$");
private static final Pattern DATE_5_PATTERN = Pattern.compile("^\\d{4}[-]\\d{2}[-]\\d{2} \\d{2}[:]\\d{2}[:]\\d{2}$");
private static final Pattern DATE_6_PATTERN = Pattern.compile("^\\d{4}[-]\\d{2}[-]\\d{2} \\d{2}[:]\\d{2}[:]\\d{2}[.]\\d{3}$");

private static final ObjectMapper MAPPER;

static {
    MAPPER = new ObjectMapper();
    MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    MAPPER.enable(serializationFeature.WRITE_DATE_KEYS_AS_@R_874_6561@AMPS);
    MAPPER.enable(serializationFeature.WRITE_DATES_AS_@R_874_6561@AMPS);
    // Long
    SimpleModule module = new SimpleModule();
    Jsonserializer<Long> longserializer = new Jsonserializer<Long>() {
        public void serialize(Long value,JsonGenerator jgen,serializerProvider provider) throws IOException,JsonProcessingException {
            if (value >= LONG_JS_MAX_VLAUE) {
                jgen.writeString(value.toString());
            } else {
                jgen.writenumber(value);
            }
        }

    };
    JsonDeserializer<? extends Long> longDeserializer = new JsonDeserializer<Long>() {
        public Long deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException,JsonProcessingException {
            return Long.valueOf(jp.getValueAsString());
        }
    };
    // BIGIntegeR
    Jsonserializer<BigInteger> bigIntserializer = new Jsonserializer<BigInteger>() {
        public void serialize(BigInteger value,serializerProvider provider)
                throws IOException,JsonProcessingException {
            if (value.longValue() >= LONG_JS_MAX_VLAUE) {
                jgen.writeString(value.toString());
            } else {
                jgen.writenumber(value);
            }
        }
    };
    // BIGdecimaL
    Jsonserializer<Bigdecimal> bigDecserializer = new Jsonserializer<Bigdecimal>() {
        public void serialize(Bigdecimal value,JsonProcessingException {
            jgen.writeString(String.valueOf(value));
        }
    };
    // DATE
    JsonDeserializer<Date> dateDeserializer = new JsonDeserializer<Date>() {
        public Date deserialize(JsonParser jp,JsonProcessingException {
            String text = jp.getValueAsString();
            if (StringUtils.isEmpty(text)) {
                return null;
            } 
            if(numbER_PATTERN.matcher(text).matches()) {
                if(DATE_2_PATTERN.matcher(text).matches() || DATE_1_PATTERN.matcher(text).matches()) {
                    return String2Date(text,"yyyymMddHHmmss");
                }
                // MS
                return new Date(Long.valueOf(text));
            }
            if(DATE_3_PATTERN.matcher(text).matches()) {
                return String2Date(text,"yyyy-MM");
            }
            if(DATE_4_PATTERN.matcher(text).matches()) {
                return String2Date(text,"yyyy-MM-dd");
            }
            if(DATE_5_PATTERN.matcher(text).matches()) {
                return String2Date(text,"yyyy-MM-dd HH:mm:ss");
            }
            if(DATE_6_PATTERN.matcher(text).matches()) {
                return String2Date(text,"yyyy-MM-dd HH:mm:ss.SSS");
            }
            throw new RuntimeException("日期数据格式不符 - " + text);
        }
    };
    module.addserializer(long.class,longserializer);
    module.addserializer(Long.class,longserializer);
    module.addserializer(BigInteger.class,bigIntserializer);
    module.addserializer(Bigdecimal.class,bigDecserializer);

    module.addDeserializer(long.class,longDeserializer);
    module.addDeserializer(Long.class,longDeserializer);
    module.addDeserializer(Date.class,dateDeserializer);
    MAPPER.registerModule(modulE);
}

private JsonUtils() {
    throw new IllegalAccessError("该类不允许实例化");
}
/**
 * 将对象转换为 JSON 的字符串格式
 * @param obj 被转换的对象
 * @return 当参数为空时会返回null
public static String object2String(Object obj) {
    if (obj == null) {
        return null;
    }
    StringWriter writer = new StringWriter();
    try {
        MAPPER.writeValue(writer,obj);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将对象[{}]转换为JSON字符串时发生异常",obj,E);
        throw new RuntimeException(message.getmessage(),E);
    }
    return writer.toString();
}
/**
 * 将 JSON 格式的字符串转换为 map
 * @param json JSON,允许为空
 * @return json为null时会返回空的Map实例
 */
public static Map<String,Object> String2Map(String json) {
    try {
        if (StringUtils.isBlank(json)) {
            return HashMap.class.newInstance();
        }
        JavaType type = TYPE_FACTORY.constructMapType(HashMap.class,String.class,Object.class);
        return MAPPER.readValue(json,typE);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将字符串[{}]转换为Map时出现异常",json);
        throw new RuntimeException(message.getmessage(),E);
    }
}
/**
 * 将 JSON 格式的字符串转换为数组
 * @param <T>
 * @param json 字符串
 * @param clz 数组类型
 * @return json为null时会返回null
 */
public static <T> T[] String2Array(String json,Class<T> clz) {
    try {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        JavaType type = TYPE_FACTORY.constructArrayType(clz);
        return (T[]) MAPPER.readValue(json,typE);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将字符串[{}]转换为数组时出现异常",json,E);
    }
}
/**
 * 将 JSON 格式的字符串转换为对象
 * @param <T>
 * @param json 字符串
 * @param clz 对象类型
 * @return json为null时会返回null
public static <T> T String2Obj(String json,Class<T> clz) {
    try {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        JavaType type = TYPE_FACTORY.constructType(clz);
        return (T) MAPPER.readValue(json,typE);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将字符串[{}]转换为对象[{}]时出现异常",new Object[] { json,clz.getSimplename(),e });
        throw new RuntimeException(message.getmessage(),E);
    }
}
/**
 * 将 JSON 格式的字符串转换为对象
 * @param <T>
 * @param json 字符串
 * @param type 对象类型
 * @return json为null时会返回null
 */
public static <T> T String2Obj(String json,Type typE) {
    try {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        JavaType t = TYPE_FACTORY.constructType(typE);
        return (T) MAPPER.readValue(json,t);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将字符串[{}]转换为对象[{}]时出现异常",type,E);
    }
}
/***
 * json 泛型转换
 * @param tr 示例 new TypeReference<List<Long>>(){}
 **/
public static <T> T String2GenericObject(String json,TypeReference<T> tr) {
    if (StringUtils.isBlank(json)) {
        return null;
    } else {
        try {
            return (T) MAPPER.readValue(json,tr);
        } catch (Exception E) {
            FormatTingTuple message = messageformatter.format("将字符串[{}]转换为[{}]时出现异常",tr });
            throw new RuntimeException(message.getmessage(),E);
        }
    }
}
/**
 * 将 JSON 格式的字符串转换为对象
 * @param <T>
 * @param json 字符串
 * @param type 对象类型
 * @return json为null时会返回null
 */
public static <T> T bytes2Object(byte[] json,Type typE) {
    try {
        if (json == null || json.length == 0) {
            return null;
        }
        JavaType t = TYPE_FACTORY.constructType(typE);
        return (T) MAPPER.readValue(json,E);
    }
}
/***
 * json数组泛型转换
 * @param tr 示例 new TypeReference<List<Long>>(){}
 **/
public static <T> T bytes2GenericObject(byte[] json,TypeReference<T> tr) {
    if (json == null || json.length == 0) {
        return null;
    } else {
        try {
            return (T) MAPPER.readValue(json,E);
        }
    }
}
/**
 * 将 JSON 格式的字符串转换为集合
 * @param <T>
 * @param json 字符串
 * @param collectionType 集合类型
 * @param elementType 元素类型
 * @return json为null时会返回空的集合实例
 */
public static <C extends Collection<E>,E> C String2Collection(String json,Class<C> collectionType,Class<E> elementTypE) {
    try {
        if (StringUtils.isBlank(json)) {
            return collectionType.newInstance();
        }
        JavaType type = TYPE_FACTORY.constructCollectionType(collectionType,elementTypE);
        return MAPPER.readValue(json,typE);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将字符串[{}]转换为集合[{}]时出现异常",collectionType.getSimplename(),E);
    }
}
/**
 * 将字符串转换{@link HashMap}对象实例
 * @param json 被转换的字符串
 * @param keyType 键类型
 * @param valueType 值类型
 * @return json为null时会返回空的HashMap实例
 */
public static <K,V> Map<K,V> String2Map(String json,Class<K> keyType,Class<V> valueTypE) {
    try {
        if (StringUtils.isBlank(json)) {
            return HashMap.class.newInstance();
        }
        JavaType type = TYPE_FACTORY.constructMapType(HashMap.class,keyType,valueTypE);
        return (Map<K,V>) MAPPER.readValue(json,E);
    }
}
/**
 * 将字符串转换为特定的{@link Map}对象实例
 * @param json 被转换的字符串
 * @param keyType 键类型
 * @param valueType 值类型
 * @param mapType 指定的{@link Map}类型
 * @return json为空时会返回空的Map实例
 */
public static <M extends Map<K,V>,K,V> M String2Map(String json,Class<V> valueType,Class<M> mapTypE) {
    try {
        if (StringUtils.isBlank(json)) {
            return mapType.newInstance();
        }
        JavaType type = TYPE_FACTORY.constructMapType(mapType,valueTypE);
        return MAPPER.readValue(json,E);
    }
}
/**
 * 将 JSON 对象类型转换
 * @param <T>
 * @param value 字符串
 * @param type 对象类型
 * @return json为null时会返回null
 */
public static <T> T convertObject(Object value,TypeReference<T> typE) {
    try {
        if (value == null) {
            return null;
        }
        JavaType t = TYPE_FACTORY.constructType(typE);
        return (T) MAPPER.convertValue(value,t);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将对象[{}]转换为类型[{}]时出现异常",new Object[] { value,E);
    }
}
/**
 * java map 转换对象
 * @param maPDAta 原始数据
 * @param tr 转换类型
 */
public static <T> T map2Object(Map<?,?> maPDAta,TypeReference<T> tr) {
    try {
        JsonNode node = MAPPER.valueToTree(maPDAta);
        return MAPPER.readValue(node.traverse(),tr);
    } catch (Exception E) {
        FormatTingTuple message = messageformatter.format("将MAP[{}]转换为[{}]时出现异常",new Object[] { maPDAta,tr });
        throw new RuntimeException(message.getmessage(),E);
    }
}

private static Date String2Date(String String,String pattern){
    try {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = format.parse(String);
        return date;
    } catch (ParseException E) {
        throw new IllegalArgumentexception("无法将字符串:"+String+"转成日期");
    }
}

}

大佬总结

以上是大佬教程为你收集整理的JsonUtils & json转换全部内容,希望文章能够帮你解决JsonUtils & json转换所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。