|
@@ -14,10 +14,7 @@ import org.slf4j.LoggerFactory;
|
|
|
|
|
|
import java.io.IOException;
|
|
|
import java.text.SimpleDateFormat;
|
|
|
-import java.util.Collection;
|
|
|
-import java.util.HashMap;
|
|
|
-import java.util.List;
|
|
|
-import java.util.Map;
|
|
|
+import java.util.*;
|
|
|
|
|
|
/**
|
|
|
* 简单封装Jackson,实现JSON 与 Java Object互相转换的Mapper
|
|
@@ -82,6 +79,7 @@ public class JsonMapper {
|
|
|
|
|
|
//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
|
|
|
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
|
|
+
|
|
|
//忽略无法转换的对象
|
|
|
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
|
|
|
|
|
@@ -107,6 +105,24 @@ public class JsonMapper {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Object 转换为 Json(美化版)
|
|
|
+ * 若对象为 null 或 转换异常时,返回null
|
|
|
+ * 若集合为空集合,返回[]
|
|
|
+ */
|
|
|
+ public String toPrettyJson(Object object) {
|
|
|
+ if (object == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
|
|
|
+ } catch (IOException e) {
|
|
|
+ LOG.error("toPrettyJson error! " + e.getMessage(), e);
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 反序列化POJO或简单Collection如List<String>
|
|
|
* 如果JSON字符串为Null或"null"字符串, 返回Null
|
|
@@ -158,6 +174,15 @@ public class JsonMapper {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Json 转换为 T[]
|
|
|
+ * 若Json字符串为 null 或 empty 或 转换异常时,返回null
|
|
|
+ */
|
|
|
+ public <T> T[] toArray(String jsonStr, Class<T> clazz) {
|
|
|
+ JavaType javaType = this.constructArrayType(clazz);
|
|
|
+ return this.parseJson(jsonStr, javaType);
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Json to List
|
|
|
*/
|
|
@@ -175,10 +200,19 @@ public class JsonMapper {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Json 转换为 Set<T>
|
|
|
+ * 若Json字符串为 null 或 empty 或 转换异常时,返回null
|
|
|
+ */
|
|
|
+ public <T> Set<T> toSet(String jsonStr, Class<T> clazz) {
|
|
|
+ JavaType javaType = this.constructCollectionType(Set.class, clazz);
|
|
|
+ return this.parseJson(jsonStr, javaType);
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Json to HashMap
|
|
|
*/
|
|
|
- public <T> Map<String, T> toHashMap(String jsonStr, Class<T> bean) {
|
|
|
+ public <T> Map<String, T> toMap(String jsonStr, Class<T> bean) {
|
|
|
if (StringUtils.isEmpty(jsonStr)) {
|
|
|
return null;
|
|
|
}
|
|
@@ -192,6 +226,13 @@ public class JsonMapper {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 构造Array类型
|
|
|
+ */
|
|
|
+ public JavaType constructArrayType(Class<?> elementClass) {
|
|
|
+ return mapper.getTypeFactory().constructArrayType(elementClass);
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 构造Collection类型
|
|
|
*/
|