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

org.macrocloud.kernel.toolkit.jackson.JsonUtil Maven / Gradle / Ivy

There is a newer version: 1.1.0-RELEASE
Show newest version
package org.macrocloud.kernel.toolkit.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.type.CollectionLikeType;
import com.fasterxml.jackson.databind.type.MapType;
import lombok.extern.slf4j.Slf4j;
import org.macrocloud.kernel.toolkit.utils.*;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.*;


/**
 * Jackson工具类.
 */

/** The Constant log. */
@Slf4j
public class JsonUtil {

	/**
	 * 将对象序列化成json字符串.
	 *
	 * @param  the generic type
	 * @param value javaBean
	 * @return jsonString json字符串
	 */
	public static  String toJson(T value) {
		try {
			return getInstance().writeValueAsString(value);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 将对象序列化成 json byte 数组.
	 *
	 * @param object javaBean
	 * @return jsonString json字符串
	 */
	public static byte[] toJsonAsBytes(Object object) {
		try {
			return getInstance().writeValueAsBytes(object);
		} catch (JsonProcessingException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param        T 泛型标记
	 * @param content   content
	 * @param valueType class
	 * @return Bean
	 */
	public static  T parse(String content, Class valueType) {
		try {
			return getInstance().readValue(content, valueType);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param content       content
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	public static  T parse(String content, TypeReference typeReference) {
		try {
			return getInstance().readValue(content, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json byte 数组反序列化成对象.
	 *
	 * @param        T 泛型标记
	 * @param bytes     json bytes
	 * @param valueType class
	 * @return Bean
	 */
	public static  T parse(byte[] bytes, Class valueType) {
		try {
			return getInstance().readValue(bytes, valueType);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}


	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param bytes         bytes
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	public static  T parse(byte[] bytes, TypeReference typeReference) {
		try {
			return getInstance().readValue(bytes, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param        T 泛型标记
	 * @param in        InputStream
	 * @param valueType class
	 * @return Bean
	 */
	public static  T parse(InputStream in, Class valueType) {
		try {
			return getInstance().readValue(in, valueType);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param in            InputStream
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	public static  T parse(InputStream in, TypeReference typeReference) {
		try {
			return getInstance().readValue(in, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成List对象.
	 *
	 * @param           T 泛型标记
	 * @param content      content
	 * @param valueTypeRef class
	 * @return List
	 */
	public static  List parseArray(String content, Class valueTypeRef) {
		try {

			if (!StringUtil.startsWithIgnoreCase(content, StringPool.LEFT_SQ_BRACKET)) {
				content = StringPool.LEFT_SQ_BRACKET + content + StringPool.RIGHT_SQ_BRACKET;
			}

			List> list = getInstance().readValue(content, new TypeReference>>() {
			});

			List result = new ArrayList<>();
			for (Map map : list) {
				result.add(toPojo(map, valueTypeRef));
			}
			return result;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 将json字符串转成 JsonNode.
	 *
	 * @param jsonString jsonString
	 * @return jsonString json字符串
	 */
	public static JsonNode readTree(String jsonString) {
		Objects.requireNonNull(jsonString, "jsonString is null");
		try {
			return getInstance().readTree(jsonString);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json字符串转成 JsonNode.
	 *
	 * @param in InputStream
	 * @return  JsonNodejsonString json字符串
	 */
	public static JsonNode readTree(InputStream in) {
		Objects.requireNonNull(in, "InputStream in is null");
		try {
			return getInstance().readTree(in);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json字符串转成 JsonNode.
	 *
	 * @param content content
	 * @return JsonNode jsonString json字符串
	 */
	public static JsonNode readTree(byte[] content) {
		Objects.requireNonNull(content, "byte[] content is null");
		try {
			return getInstance().readTree(content);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json字符串转成 JsonNode.
	 *
	 * @param jsonParser JsonParser
	 * @return JsonNode jsonString json字符串
	 */
	public static JsonNode readTree(JsonParser jsonParser) {
		Objects.requireNonNull(jsonParser, "jsonParser is null");
		try {
			return getInstance().readTree(jsonParser);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}


	/**
	 * 将json byte 数组反序列化成对象.
	 *
	 * @param        T 泛型标记
	 * @param content   json bytes
	 * @param valueType class
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable byte[] content, Class valueType) {
		if (ObjectUtil.isEmpty(content)) {
			return null;
		}
		try {
			return getInstance().readValue(content, valueType);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param         T 泛型标记
	 * @param jsonString jsonString
	 * @param valueType  class
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable String jsonString, Class valueType) {
		if (StringUtil.isBlank(jsonString)) {
			return null;
		}
		try {
			return getInstance().readValue(jsonString, valueType);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param        T 泛型标记
	 * @param in        InputStream
	 * @param valueType class
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable InputStream in, Class valueType) {
		if (in == null) {
			return null;
		}
		try {
			return getInstance().readValue(in, valueType);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param content       bytes
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable byte[] content, TypeReference typeReference) {
		if (ObjectUtil.isEmpty(content)) {
			return null;
		}
		try {
			return getInstance().readValue(content, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param jsonString    jsonString
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable String jsonString, TypeReference typeReference) {
		if (StringUtil.isBlank(jsonString)) {
			return null;
		}
		try {
			return getInstance().readValue(jsonString, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 将json反序列化成对象.
	 *
	 * @param            T 泛型标记
	 * @param in            InputStream
	 * @param typeReference 泛型类型
	 * @return Bean
	 */
	@Nullable
	public static  T readValue(@Nullable InputStream in, TypeReference typeReference) {
		if (in == null) {
			return null;
		}
		try {
			return getInstance().readValue(in, typeReference);
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 封装 map type.
	 *
	 * @param keyClass   key 类型
	 * @param valueClass value 类型
	 * @return MapType
	 */
	public static MapType getMapType(Class keyClass, Class valueClass) {
		return getInstance().getTypeFactory().constructMapType(Map.class, keyClass, valueClass);
	}

	/**
	 * 封装 map type.
	 *
	 * @param elementClass 集合值类型
	 * @return CollectionLikeType
	 */
	public static CollectionLikeType getListType(Class elementClass) {
		return getInstance().getTypeFactory().constructCollectionLikeType(List.class, elementClass);
	}

	/**
	 * 读取集合.
	 *
	 * @param           泛型
	 * @param content      bytes
	 * @param elementClass elementClass
	 * @return 集合
	 */
	public static  List readList(@Nullable byte[] content, Class elementClass) {
		if (ObjectUtil.isEmpty(content)) {
			return Collections.emptyList();
		}
		try {
			return getInstance().readValue(content, getListType(elementClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 读取集合.
	 *
	 * @param           泛型
	 * @param content      InputStream
	 * @param elementClass elementClass
	 * @return 集合
	 */
	public static  List readList(@Nullable InputStream content, Class elementClass) {
		if (content == null) {
			return Collections.emptyList();
		}
		try {
			return getInstance().readValue(content, getListType(elementClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 读取集合.
	 *
	 * @param           泛型
	 * @param content      bytes
	 * @param elementClass elementClass
	 * @return 集合
	 */
	public static  List readList(@Nullable String content, Class elementClass) {
		if (ObjectUtil.isEmpty(content)) {
			return Collections.emptyList();
		}
		try {
			return getInstance().readValue(content, getListType(elementClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 读取集合.
	 *
	 * @param         泛型
	 * @param         泛型
	 * @param content    bytes
	 * @param keyClass   key类型
	 * @param valueClass 值类型
	 * @return 集合
	 */
	public static  Map readMap(@Nullable byte[] content, Class keyClass, Class valueClass) {
		if (ObjectUtil.isEmpty(content)) {
			return Collections.emptyMap();
		}
		try {
			return getInstance().readValue(content, getMapType(keyClass, valueClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 读取集合.
	 *
	 * @param         泛型
	 * @param         泛型
	 * @param content    InputStream
	 * @param keyClass   key类型
	 * @param valueClass 值类型
	 * @return 集合
	 */
	public static  Map readMap(@Nullable InputStream content, Class keyClass, Class valueClass) {
		if (ObjectUtil.isEmpty(content)) {
			return Collections.emptyMap();
		}
		try {
			return getInstance().readValue(content, getMapType(keyClass, valueClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 读取集合.
	 *
	 * @param         泛型
	 * @param         泛型
	 * @param content    bytes
	 * @param keyClass   key类型
	 * @param valueClass 值类型
	 * @return 集合
	 */
	public static  Map readMap(@Nullable String content, Class keyClass, Class valueClass) {
		if (ObjectUtil.isEmpty(content)) {
			return Collections.emptyMap();
		}
		try {
			return getInstance().readValue(content, getMapType(keyClass, valueClass));
		} catch (IOException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * jackson 的类型转换.
	 *
	 * @param          泛型标记
	 * @param fromValue   来源对象
	 * @param toValueType 转换的类型
	 * @return 转换结果
	 */
	public static  T convertValue(Object fromValue, Class toValueType) {
		return getInstance().convertValue(fromValue, toValueType);
	}

	/**
	 * jackson 的类型转换.
	 *
	 * @param          泛型标记
	 * @param fromValue   来源对象
	 * @param toValueType 转换的类型
	 * @return 转换结果
	 */
	public static  T convertValue(Object fromValue, JavaType toValueType) {
		return getInstance().convertValue(fromValue, toValueType);
	}

	/**
	 * jackson 的类型转换.
	 *
	 * @param             泛型标记
	 * @param fromValue      来源对象
	 * @param toValueTypeRef 泛型类型
	 * @return 转换结果
	 */
	public static  T convertValue(Object fromValue, TypeReference toValueTypeRef) {
		return getInstance().convertValue(fromValue, toValueTypeRef);
	}

	/**
	 * tree 转对象.
	 *
	 * @param        泛型标记
	 * @param treeNode  TreeNode
	 * @param valueType valueType
	 * @return 转换结果
	 */
	public static  T treeToValue(TreeNode treeNode, Class valueType) {
		try {
			return getInstance().treeToValue(treeNode, valueType);
		} catch (JsonProcessingException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 对象转为 json node.
	 *
	 * @param value 对象
	 * @return JsonNode
	 */
	public static JsonNode valueToTree(@Nullable Object value) {
		return getInstance().valueToTree(value);
	}

	/**
	 * 判断是否可以序列化.
	 *
	 * @param value 对象
	 * @return 是否可以序列化
	 */
	public static boolean canSerialize(@Nullable Object value) {
		if (value == null) {
			return true;
		}
		return getInstance().canSerialize(value.getClass());
	}

	/**
	 * To map.
	 *
	 * @param content the content
	 * @return the map
	 */
	public static Map toMap(String content) {
		try {
			return getInstance().readValue(content, Map.class);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * To map.
	 *
	 * @param  the generic type
	 * @param content the content
	 * @param valueTypeRef the value type ref
	 * @return the map
	 */
	public static  Map toMap(String content, Class valueTypeRef) {
		try {
			Map> map = getInstance().readValue(content, new TypeReference>>() {
			});
			Map result = new HashMap<>(16);
			for (Map.Entry> entry : map.entrySet()) {
				result.put(entry.getKey(), toPojo(entry.getValue(), valueTypeRef));
			}
			return result;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * To pojo.
	 *
	 * @param  the generic type
	 * @param fromValue the from value
	 * @param toValueType the to value type
	 * @return the t
	 */
	public static  T toPojo(Map fromValue, Class toValueType) {
		return getInstance().convertValue(fromValue, toValueType);
	}

	/**
	 * Gets the single instance of JsonUtil.
	 *
	 * @return single instance of JsonUtil
	 */
	public static ObjectMapper getInstance() {
		return JacksonHolder.INSTANCE;
	}

	/**
	 * The Class JacksonHolder.
	 */
	private static class JacksonHolder {
		
		/** The Constant INSTANCE. */
		private static final ObjectMapper INSTANCE = new JacksonObjectMapper();
	}

	/**
	 * The Class JacksonObjectMapper.
	 */
	private static class JacksonObjectMapper extends ObjectMapper {
		
		/** The Constant serialVersionUID. */
		private static final long serialVersionUID = 4288193147502386170L;

		/** The Constant CHINA. */
		private static final Locale CHINA = Locale.CHINA;

		/**
		 * Instantiates a new jackson object mapper.
		 *
		 * @param src the src
		 */
		public JacksonObjectMapper(ObjectMapper src) {
			super(src);
		}

		/**
		 * Instantiates a new jackson object mapper.
		 */
		public JacksonObjectMapper() {
			super();
			//设置地点为中国
			super.setLocale(CHINA);
			//去掉默认的时间戳格式
			super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
			//设置为中国上海时区
			super.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
			//序列化时,日期的统一格式
			super.setDateFormat(new SimpleDateFormat(DateUtil.PATTERN_DATETIME, Locale.CHINA));
			// 单引号
			super.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
			// 允许JSON字符串包含非引号控制字符(值小于32的ASCII字符,包含制表符和换行符)
			super.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
			super.configure(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature(), true);
			super.findAndRegisterModules();
			//失败处理
			super.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			//单引号处理
			super.configure(JsonReadFeature.ALLOW_SINGLE_QUOTES.mappedFeature(), true);
			//反序列化时,属性不存在的兼容处理s
			super.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			//日期格式化
			super.registerModule(new BaseJavaTimeModule());
			super.findAndRegisterModules();
		}

		/**
		* 

Title: copy

*

Description:

* @return * @see com.fasterxml.jackson.databind.ObjectMapper#copy() */ @Override public ObjectMapper copy() { return new JacksonObjectMapper(this); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy