From b15036d2fdffa33a8583def95c9194b35ba42d4a Mon Sep 17 00:00:00 2001 From: 1099815072@qq.com <1099815072@qq.com> Date: Fri, 13 Nov 2020 09:33:51 +0800 Subject: [PATCH] json工具类提交 --- cloud/dahua/src/main/java/com/example/dahua/utils/JsonUtils.java | 133 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+), 0 deletions(-) create mode 100644 cloud/dahua/src/main/java/com/example/dahua/utils/JsonUtils.java diff --git a/cloud/dahua/src/main/java/com/example/dahua/utils/JsonUtils.java b/cloud/dahua/src/main/java/com/example/dahua/utils/JsonUtils.java new file mode 100644 index 0000000..deb883e --- /dev/null +++ b/cloud/dahua/src/main/java/com/example/dahua/utils/JsonUtils.java @@ -0,0 +1,133 @@ +package com.example.dahua.utils; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.Map; + +/** + * 类JsonMapper.java的实现描述:简单封装Jackson,实现JSON String<->Java Object的Mapper. + * + *
封装不同的输出风格, 使用不同的builder函数创建实例.
+ * + * @author xuquan + */ +public class JsonUtils { + + private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class); + + private ObjectMapper mapper; + + public JsonUtils(){ + this(null); + } + + public JsonUtils(Include include) { + mapper = new ObjectMapper(); + // 设置输出时包含属性的风格 + if (include != null) { + mapper.setSerializationInclusion(include); + } + // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + } + + /** + * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用. + */ + public static JsonUtils nonEmptyMapper() { + return new JsonUtils(Include.NON_EMPTY); + } + + /** + * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。 + */ + public static JsonUtils nonDefaultMapper() { + return new JsonUtils(Include.NON_DEFAULT); + } + + /** + * Object可以是POJO,也可以是Collection或数组。 + * 如果对象为Null, 返回"null". + * 如果集合为空集合, 返回"[]". + */ + public String toJson(Object object) { + + try { + return mapper.writeValueAsString(object); + } catch (IOException e) { + LOG.warn(String.format("序列化成 JSON 字符串发生错误:%s", object), e); + return null; + } + } + + /** + * 反序列化POJO或简单Collection如List