JsonUtils.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package com.ruoyi.common.utils;
  2. import cn.hutool.core.util.ArrayUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * JSON 工具类
  13. *
  14. * @author 芋道源码
  15. */
  16. public class JsonUtils {
  17. private static ObjectMapper objectMapper = new ObjectMapper();
  18. /**
  19. * 初始化 objectMapper 属性
  20. * <p>
  21. * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
  22. *
  23. * @param objectMapper ObjectMapper 对象
  24. */
  25. public static void init(ObjectMapper objectMapper) {
  26. JsonUtils.objectMapper = objectMapper;
  27. }
  28. public static String toJsonString(Object object) {
  29. try {
  30. return objectMapper.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 (StrUtil.isEmpty(text)) {
  37. return null;
  38. }
  39. try {
  40. return objectMapper.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 objectMapper.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. try {
  57. return objectMapper.readValue(text, typeReference);
  58. } catch (IOException e) {
  59. throw new RuntimeException(e);
  60. }
  61. }
  62. public static <T> Map<String, T> parseMap(String text) {
  63. try {
  64. return objectMapper.readValue(text, new TypeReference<Map<String, T>>() {});
  65. } catch (IOException e) {
  66. throw new RuntimeException(e);
  67. }
  68. }
  69. public static <T> List<T> parseArray(String text, Class<T> clazz) {
  70. if (StrUtil.isEmpty(text)) {
  71. return new ArrayList<>();
  72. }
  73. try {
  74. return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
  75. } catch (IOException e) {
  76. throw new RuntimeException(e);
  77. }
  78. }
  79. }