12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- 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 <T> List<T> getList(String json,Class<T> cls){
- try {
- return mapper.readValue(json, new TypeReference<List<T>>() {});
- }
- catch(Exception e) {
- throw new RuntimeException("jackson参数转换出错");
- }
-
- }
-
- public static <T> List<T> getList2(String json,Class<T> 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<Map<String,Object>> getMaps(String json){
- try {
- return mapper.readValue(json, new TypeReference<List<Map<String,Object>>>() {});
- }
- catch(Exception e) {
- throw new RuntimeException("jackson参数转换出错");
- }
-
- }
-
- @SuppressWarnings("unchecked")
- public static Map<String,Object> getMap(String json){
- try {
- return mapper.readValue(json, Map.class);
- }
- catch(Exception e) {
- throw new RuntimeException("jackson参数转换出错");
- }
- }
-
- public static <T> T get(String json,Class<T> cls) {
- try {
- return mapper.readValue(json, cls);
- }
- catch(Exception e) {
- throw new RuntimeException("jackson参数转换出错");
- }
- }
-
- public static <T> T readFile(File file,Class<T> 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();
- }
- }
- }
|