JacksonUtils.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.hb.proj.utils;
  2. import java.util.List;
  3. import java.util.Map;
  4. import com.fasterxml.jackson.core.type.TypeReference;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. public class JacksonUtils {
  7. //private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);
  8. private final static ObjectMapper mapper = new ObjectMapper();
  9. public static String getJSON(Object obj){
  10. try {
  11. return mapper.writeValueAsString(obj);
  12. }
  13. catch(Exception e) {
  14. throw new RuntimeException("jackson序列化对象时出错");
  15. }
  16. }
  17. public static <T> List<T> getList(String json,Class<T> cls){
  18. try {
  19. return mapper.readValue(json, new TypeReference<List<T>>() {});
  20. }
  21. catch(Exception e) {
  22. throw new RuntimeException("jackson参数转换出错");
  23. }
  24. }
  25. public static List<Map<String,Object>> getMaps(String json){
  26. try {
  27. return mapper.readValue(json, new TypeReference<List<Map<String,Object>>>() {});
  28. }
  29. catch(Exception e) {
  30. throw new RuntimeException("jackson参数转换出错");
  31. }
  32. }
  33. @SuppressWarnings("unchecked")
  34. public static Map<String,Object> getMap(String json){
  35. try {
  36. return mapper.readValue(json, Map.class);
  37. }
  38. catch(Exception e) {
  39. throw new RuntimeException("jackson参数转换出错");
  40. }
  41. }
  42. public static <T> T get(String json,Class<T> cls) {
  43. try {
  44. return mapper.readValue(json, cls);
  45. }
  46. catch(Exception e) {
  47. throw new RuntimeException("jackson参数转换出错");
  48. }
  49. }
  50. }