package com.hb.proj.utils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; public class JacksonUtils { //private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class); private final static ObjectMapper mapper = new ObjectMapper(); public static String getJSON(Object obj){ try { return mapper.writeValueAsString(obj); } catch(Exception e) { throw new RuntimeException("jackson序列化对象时出错"); } } public static List getList(String json,Class cls){ try { return mapper.readValue(json, new TypeReference>() {}); } catch(Exception e) { throw new RuntimeException("jackson参数转换出错"); } } public static List getList2(String json,Class cls){ try { CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, cls); return mapper.readValue(json,listType); } catch(Exception e) { throw new RuntimeException("jackson参数转换出错"); } } public static List> getMaps(String json){ try { return mapper.readValue(json, new TypeReference>>() {}); } catch(Exception e) { throw new RuntimeException("jackson参数转换出错"); } } @SuppressWarnings("unchecked") public static Map getMap(String json){ try { return mapper.readValue(json, Map.class); } catch(Exception e) { throw new RuntimeException("jackson参数转换出错"); } } public static T get(String json,Class cls) { try { return mapper.readValue(json, cls); } catch(Exception e) { throw new RuntimeException("jackson参数转换出错"); } } public static T readFile(File file,Class cls) { try{ return mapper.readValue(file, cls); } catch(Exception e) { throw new RuntimeException("jackson参数json文件转换出错"); } } public static void writeFile(File file,Object datas) { try { mapper.writeValue(file, datas); } catch (Exception e) { e.printStackTrace(); } } }