JsonUtils.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cn.iocoder.dashboard.util.json;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.core.type.TypeReference;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import java.io.IOException;
  6. import java.util.Set;
  7. /**
  8. * JSON 工具类
  9. *
  10. * @author 芋道源码
  11. */
  12. public class JsonUtils {
  13. private static ObjectMapper objectMapper = new ObjectMapper();
  14. /**
  15. * 初始化 objectMapper 属性
  16. *
  17. * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
  18. *
  19. * @param objectMapper ObjectMapper 对象
  20. */
  21. public static void init(ObjectMapper objectMapper) {
  22. JsonUtils.objectMapper = objectMapper;
  23. }
  24. public static String toJsonString(Object object) {
  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. try {
  33. return objectMapper.readValue(text, clazz);
  34. } catch (IOException e) {
  35. throw new RuntimeException(e);
  36. }
  37. }
  38. public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
  39. try {
  40. return objectMapper.readValue(bytes, clazz);
  41. } catch (IOException e) {
  42. throw new RuntimeException(e);
  43. }
  44. }
  45. public static Object parseObject(String text, TypeReference<Set<Long>> typeReference) {
  46. try {
  47. return objectMapper.readValue(text, typeReference);
  48. } catch (IOException e) {
  49. throw new RuntimeException(e);
  50. }
  51. }
  52. }