Jackson常用工具类

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11983194.html

Demo

 1 package org.fool.util;
 2 
 3 import com.fasterxml.jackson.core.JsonProcessingException;
 4 import com.fasterxml.jackson.databind.JavaType;
 5 import com.fasterxml.jackson.databind.ObjectMapper;
 6 
 7 import java.util.List;
 8 import java.util.Map;
 9 
10 public class JsonUtils {
11     private static final ObjectMapper MAPPER = new ObjectMapper();
12 
13     public static String objectToJson(Object data) {
14         try {
15             String result = MAPPER.writeValueAsString(data);
16             return result;
17         } catch (JsonProcessingException e) {
18             e.printStackTrace();
19         }
20         return null;
21     }
22 
23     public static <T> T jsonToBean(String jsonData, Class<T> beanType) {
24         try {
25             T result = MAPPER.readValue(jsonData, beanType);
26             return result;
27         } catch (Exception e) {
28             e.printStackTrace();
29         }
30 
31         return null;
32     }
33 
34     public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
35         JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
36 
37         try {
38             List<T> resultList = MAPPER.readValue(jsonData, javaType);
39             return resultList;
40         } catch (Exception e) {
41             e.printStackTrace();
42         }
43 
44         return null;
45     }
46 
47     public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) {
48         JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType);
49 
50         try {
51             Map<K, V> resultMap = MAPPER.readValue(jsonData, javaType);
52             return resultMap;
53         } catch (Exception e) {
54             e.printStackTrace();
55         }
56 
57         return null;
58     }
59 }
原文地址:https://www.cnblogs.com/agilestyle/p/11983194.html