JsonUtils.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package com.ruoyi.common.utils;
  2. import cn.hutool.core.lang.Validator;
  3. import cn.hutool.core.util.ArrayUtil;
  4. import cn.hutool.core.util.StrUtil;
  5. import com.fasterxml.jackson.core.JsonProcessingException;
  6. import com.fasterxml.jackson.core.type.TypeReference;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Map;
  12. /**
  13. * JSON 工具类
  14. *
  15. * @author 芋道源码
  16. */
  17. public class JsonUtils {
  18. private static ObjectMapper objectMapper = new ObjectMapper();
  19. /**
  20. * 初始化 objectMapper 属性
  21. * <p>
  22. * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
  23. *
  24. * @param objectMapper ObjectMapper 对象
  25. */
  26. public static void init(ObjectMapper objectMapper) {
  27. JsonUtils.objectMapper = objectMapper;
  28. }
  29. public static String toJsonString(Object object) {
  30. if (Validator.isEmpty(object)) {
  31. return null;
  32. }
  33. try {
  34. return objectMapper.writeValueAsString(object);
  35. } catch (JsonProcessingException e) {
  36. throw new RuntimeException(e);
  37. }
  38. }
  39. public static <T> T parseObject(String text, Class<T> clazz) {
  40. if (StrUtil.isEmpty(text)) {
  41. return null;
  42. }
  43. try {
  44. return objectMapper.readValue(text, clazz);
  45. } catch (IOException e) {
  46. throw new RuntimeException(e);
  47. }
  48. }
  49. public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
  50. if (ArrayUtil.isEmpty(bytes)) {
  51. return null;
  52. }
  53. try {
  54. return objectMapper.readValue(bytes, clazz);
  55. } catch (IOException e) {
  56. throw new RuntimeException(e);
  57. }
  58. }
  59. public static <T> T parseObject(String text, TypeReference<T> typeReference) {
  60. if (StrUtil.isBlank(text)) {
  61. return null;
  62. }
  63. try {
  64. return objectMapper.readValue(text, typeReference);
  65. } catch (IOException e) {
  66. throw new RuntimeException(e);
  67. }
  68. }
  69. public static <T> Map<String, T> parseMap(String text) {
  70. if (StrUtil.isBlank(text)) {
  71. return null;
  72. }
  73. try {
  74. return objectMapper.readValue(text, new TypeReference<Map<String, T>>() {});
  75. } catch (IOException e) {
  76. throw new RuntimeException(e);
  77. }
  78. }
  79. public static <T> List<T> parseArray(String text, Class<T> clazz) {
  80. if (StrUtil.isEmpty(text)) {
  81. return new ArrayList<>();
  82. }
  83. try {
  84. return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
  85. } catch (IOException e) {
  86. throw new RuntimeException(e);
  87. }
  88. }
  89. }