From d6191d727f5ef12ebe4fcddc05df66bc2d8d1cb2 Mon Sep 17 00:00:00 2001 From: p97balmkq <1348817836@qq.com> Date: Fri, 28 Jun 2024 22:29:20 +0800 Subject: [PATCH] ADD file via upload --- JsonUtils.java | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 JsonUtils.java diff --git a/JsonUtils.java b/JsonUtils.java new file mode 100644 index 0000000..02d8a41 --- /dev/null +++ b/JsonUtils.java @@ -0,0 +1,65 @@ +package com.gk.study.utils; + +import com.baomidou.mybatisplus.core.toolkit.ArrayUtils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +public class JsonUtils { + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public static String toJsonString(Object object) { + try { + return objectMapper.writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, Class clazz) { + if (StringUtils.isEmpty(text)) { + return null; + } + try { + return objectMapper.readValue(text, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(byte[] bytes, Class clazz) { + if (bytes == null || bytes.length <= 0) { + return null; + } + try { + return objectMapper.readValue(bytes, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, TypeReference typeReference) { + try { + return objectMapper.readValue(text, typeReference); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static List parseArray(String text, Class clazz) { + if (StringUtils.isEmpty(text)) { + return new ArrayList<>(); + } + try { + return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} + +