1 package com.xxx.common.util; 2 3 import java.util.List; 4 import com.fasterxml.jackson.core.JsonProcessingException; 5 import com.fasterxml.jackson.databind.JavaType; 6 import com.fasterxml.jackson.databind.ObjectMapper; 7 8 public class JSONUtil { 9 10 // 定义jackson对象 11 private static final ObjectMapper mapper = new ObjectMapper(); 12 /** 13 * 将对象转换成json字符串 14 * @param data 15 * @return 16 */ 17 public static String toJSONString(Object data) { 18 try { 19 String string = mapper.writeValueAsString(data); 20 return string; 21 } catch (JsonProcessingException e) { 22 e.printStackTrace(); 23 } 24 return null; 25 } 26 27 /** 28 * 将json结果集转化为对象 29 * @param jsonData 30 * @param beanType 31 * @return 32 */ 33 public static <T> T parseObject(String jsonData, Class<T> beanType) { 34 try { 35 T t = mapper.readValue(jsonData, beanType); 36 return t; 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 return null; 41 } 42 43 /** 44 * 将json数据转换成list 45 * @param jsonData 46 * @param beanType 47 * @return 48 */ 49 public static <T> List<T> parseArray(String jsonData, Class<T> beanType) { 50 JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType); 51 try { 52 List<T> list = mapper.readValue(jsonData, javaType); 53 return list; 54 } catch (Exception e) { 55 e.printStackTrace(); 56 } 57 return null; 58 } 59 }