JacksonUtils.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.hb.proj.utils;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import com.fasterxml.jackson.core.type.TypeReference;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import com.fasterxml.jackson.databind.type.CollectionType;
  9. public class JacksonUtils {
  10. //private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);
  11. private final static ObjectMapper mapper = new ObjectMapper();
  12. public static String getJSON(Object obj){
  13. try {
  14. return mapper.writeValueAsString(obj);
  15. }
  16. catch(Exception e) {
  17. throw new RuntimeException("jackson序列化对象时出错");
  18. }
  19. }
  20. public static <T> List<T> getList(String json,Class<T> cls){
  21. try {
  22. return mapper.readValue(json, new TypeReference<List<T>>() {});
  23. }
  24. catch(Exception e) {
  25. throw new RuntimeException("jackson参数转换出错");
  26. }
  27. }
  28. public static <T> List<T> getList2(String json,Class<T> cls){
  29. try {
  30. CollectionType listType =
  31. mapper.getTypeFactory().constructCollectionType(ArrayList.class, cls);
  32. return mapper.readValue(json,listType);
  33. }
  34. catch(Exception e) {
  35. throw new RuntimeException("jackson参数转换出错");
  36. }
  37. }
  38. public static List<Map<String,Object>> getMaps(String json){
  39. try {
  40. return mapper.readValue(json, new TypeReference<List<Map<String,Object>>>() {});
  41. }
  42. catch(Exception e) {
  43. throw new RuntimeException("jackson参数转换出错");
  44. }
  45. }
  46. @SuppressWarnings("unchecked")
  47. public static Map<String,Object> getMap(String json){
  48. try {
  49. return mapper.readValue(json, Map.class);
  50. }
  51. catch(Exception e) {
  52. throw new RuntimeException("jackson参数转换出错");
  53. }
  54. }
  55. public static <T> T get(String json,Class<T> cls) {
  56. try {
  57. return mapper.readValue(json, cls);
  58. }
  59. catch(Exception e) {
  60. throw new RuntimeException("jackson参数转换出错");
  61. }
  62. }
  63. public static <T> T readFile(File file,Class<T> cls) {
  64. try{
  65. return mapper.readValue(file, cls);
  66. }
  67. catch(Exception e) {
  68. throw new RuntimeException("jackson参数json文件转换出错");
  69. }
  70. }
  71. public static void writeFile(File file,Object datas) {
  72. try {
  73. mapper.writeValue(file, datas);
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }