JSONUtils.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package cn.iocoder.dashboard.util.json;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import java.io.IOException;
  5. /**
  6. * JSON 工具类
  7. *
  8. * @author 芋道源码
  9. */
  10. public class JSONUtils {
  11. private static ObjectMapper objectMapper = new ObjectMapper();
  12. // TODO 芋艿,需要将 Spring 的设置下进来
  13. public static void setObjectMapper(ObjectMapper objectMapper) {
  14. JSONUtils.objectMapper = objectMapper;
  15. }
  16. public static String toJSONString(Object object) {
  17. try {
  18. return objectMapper.writeValueAsString(object);
  19. } catch (JsonProcessingException e) {
  20. throw new RuntimeException(e);
  21. }
  22. }
  23. public static <T> T parseObject(String text, Class<T> clazz) {
  24. try {
  25. return objectMapper.readValue(text, clazz);
  26. } catch (IOException e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
  31. try {
  32. return objectMapper.readValue(bytes, clazz);
  33. } catch (IOException e) {
  34. throw new RuntimeException(e);
  35. }
  36. }
  37. }