JsonUtils.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package com.ruoyi.common.utils;
  2. import cn.hutool.core.util.ArrayUtil;
  3. import cn.hutool.core.util.ObjectUtil;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.ruoyi.common.utils.spring.SpringUtils;
  8. import lombok.AccessLevel;
  9. import lombok.NoArgsConstructor;
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.Map;
  14. /**
  15. * JSON 工具类
  16. *
  17. * @author 芋道源码
  18. */
  19. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  20. public class JsonUtils {
  21. private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);
  22. public static ObjectMapper getObjectMapper() {
  23. return OBJECT_MAPPER;
  24. }
  25. public static String toJsonString(Object object) {
  26. if (ObjectUtil.isNull(object)) {
  27. return null;
  28. }
  29. try {
  30. return OBJECT_MAPPER.writeValueAsString(object);
  31. } catch (JsonProcessingException e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. public static <T> T parseObject(String text, Class<T> clazz) {
  36. if (StringUtils.isEmpty(text)) {
  37. return null;
  38. }
  39. try {
  40. return OBJECT_MAPPER.readValue(text, clazz);
  41. } catch (IOException e) {
  42. throw new RuntimeException(e);
  43. }
  44. }
  45. public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
  46. if (ArrayUtil.isEmpty(bytes)) {
  47. return null;
  48. }
  49. try {
  50. return OBJECT_MAPPER.readValue(bytes, clazz);
  51. } catch (IOException e) {
  52. throw new RuntimeException(e);
  53. }
  54. }
  55. public static <T> T parseObject(String text, TypeReference<T> typeReference) {
  56. if (StringUtils.isBlank(text)) {
  57. return null;
  58. }
  59. try {
  60. return OBJECT_MAPPER.readValue(text, typeReference);
  61. } catch (IOException e) {
  62. throw new RuntimeException(e);
  63. }
  64. }
  65. public static <T> Map<String, T> parseMap(String text) {
  66. if (StringUtils.isBlank(text)) {
  67. return null;
  68. }
  69. try {
  70. return OBJECT_MAPPER.readValue(text, new TypeReference<Map<String, T>>() {
  71. });
  72. } catch (IOException e) {
  73. throw new RuntimeException(e);
  74. }
  75. }
  76. public static <T> List<T> parseArray(String text, Class<T> clazz) {
  77. if (StringUtils.isEmpty(text)) {
  78. return new ArrayList<>();
  79. }
  80. try {
  81. return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
  82. } catch (IOException e) {
  83. throw new RuntimeException(e);
  84. }
  85. }
  86. }