JsonUtils.java 1.8 KB

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