JsonUtils.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package cn.iocoder.dashboard.util.json;
  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. /**
  11. * JSON 工具类
  12. *
  13. * @author 芋道源码
  14. */
  15. public class JsonUtils {
  16. private static ObjectMapper objectMapper = new ObjectMapper();
  17. /**
  18. * 初始化 objectMapper 属性
  19. * <p>
  20. * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
  21. *
  22. * @param objectMapper ObjectMapper 对象
  23. */
  24. public static void init(ObjectMapper objectMapper) {
  25. JsonUtils.objectMapper = objectMapper;
  26. }
  27. public static String toJsonString(Object object) {
  28. try {
  29. return objectMapper.writeValueAsString(object);
  30. } catch (JsonProcessingException e) {
  31. throw new RuntimeException(e);
  32. }
  33. }
  34. public static <T> T parseObject(String text, Class<T> clazz) {
  35. if (StrUtil.isEmpty(text)) {
  36. return null;
  37. }
  38. try {
  39. return objectMapper.readValue(text, clazz);
  40. } catch (IOException e) {
  41. throw new RuntimeException(e);
  42. }
  43. }
  44. public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
  45. if (ArrayUtil.isEmpty(bytes)) {
  46. return null;
  47. }
  48. try {
  49. return objectMapper.readValue(bytes, clazz);
  50. } catch (IOException e) {
  51. throw new RuntimeException(e);
  52. }
  53. }
  54. public static <T> T parseObject(String text, TypeReference<T> typeReference) {
  55. try {
  56. return objectMapper.readValue(text, typeReference);
  57. } catch (IOException e) {
  58. throw new RuntimeException(e);
  59. }
  60. }
  61. public static <T> List<T> parseArray(String text, Class<T> clazz) {
  62. if (StrUtil.isEmpty(text)) {
  63. return new ArrayList<>();
  64. }
  65. try {
  66. return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
  67. } catch (IOException e) {
  68. throw new RuntimeException(e);
  69. }
  70. }
  71. }