JsonUtils.java 2.5 KB

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