From 28096072d92467c582c51e84d4a81b372481868b Mon Sep 17 00:00:00 2001 From: makejava <1353036300@qq.com> Date: Thu, 1 Nov 2018 09:57:54 +0800 Subject: [PATCH] =?UTF-8?q?=E9=92=88=E5=AF=B9=E5=85=A8=E5=B1=80=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E6=B7=BB=E5=8A=A0json=E5=A4=84=E7=90=86=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/sjhy/plugin/tool/GlobalTool.java | 58 +++++++++++++++++++ .../description/templateDescription.html | 2 + 2 files changed, 60 insertions(+) diff --git a/src/main/java/com/sjhy/plugin/tool/GlobalTool.java b/src/main/java/com/sjhy/plugin/tool/GlobalTool.java index 10df03d..e6e44ab 100644 --- a/src/main/java/com/sjhy/plugin/tool/GlobalTool.java +++ b/src/main/java/com/sjhy/plugin/tool/GlobalTool.java @@ -25,6 +25,11 @@ import java.util.*; public class GlobalTool extends NameUtils { private static volatile GlobalTool globalTool; + /** + * Jackson对象 + */ + private ObjectMapper objectMapper = new ObjectMapper(); + /** * 私有构造方法 */ @@ -219,6 +224,59 @@ public class GlobalTool extends NameUtils { return builder.toString(); } + /** + * 将json转map + * + * @param json json字符串 + * @return map对象 + */ + public Map parseJson(String json) { + if (StringUtils.isEmpty(json)) { + return null; + } + try { + return objectMapper.readValue(json, Map.class); + } catch (IOException e) { + return Collections.emptyMap(); + } + } + + /** + * 将对象转json字符串 + * + * @param obj 对象 + * @return json字符串 + */ + public String toJson(Object obj) { + return toJson(obj, false); + } + + /** + * 将对象转json字符串 + * + * @param obj 对象 + * @param format 是否格式化json + * @return json字符串 + */ + public String toJson(Object obj, Boolean format) { + if (obj == null) { + return null; + } + if (format == null) { + format = false; + } + try { + // 是否格式化输出json + if (format) { + return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); + } else { + return objectMapper.writeValueAsString(obj); + } + } catch (JsonProcessingException e) { + return null; + } + } + /** * 远程调用服务 * diff --git a/src/main/resources/description/templateDescription.html b/src/main/resources/description/templateDescription.html index 8b78cb3..639d216 100644 --- a/src/main/resources/description/templateDescription.html +++ b/src/main/resources/description/templateDescription.html @@ -55,6 +55,8 @@ debug(Object obj) 调式方法,用于查询对象结构.可查看对象所有属性与public方法 serial() 随机获取序列化的UID service(String serviceName, Object... param)远程服务调用 + parseJson(String) 将字符串转Map对象 + toJson(Object, Boolean) 将对象转json对象,Boolean:是否格式化json,不填时为不格式化。 $time currTime(String format) 获取当前时间,指定时间格式(默认:yyyy-MM-dd HH:mm:ss)