sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Json使用 jackjson 工具类

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static JsonGenerator jsonGenerator = JsonUtil.getJsonGenerator();

    private static Logger log = LoggerFactory.getLogger(JsonUtil.class);

    private static JsonGenerator getJsonGenerator() {
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
            return jsonGenerator;
        } catch (IOException e) {
            log.error("get JsonGenerator error!" + e.toString());
            return null;
        }
    }

    /**
     * 把Java对象转换成json串
     *
     * @throws IOException
     */
    public static String writeEntity2Json(Object object) throws IOException {
        if (null == object) {
            log.error("class:JsonUtil,method:writeEntity2Json,param:object == null");
            return null;
        }
        log.debug("class:JsonUtil,method:writeEntity2Json,param:object=" + object);
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 把List转换成json串
     *
     * @param list
     * @return
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static String writeList2Json(List list) throws IOException {
        return objectMapper.writeValueAsString(list);
    }

    /**
     * 把List<Object>转换成List<json串>
     *
     * @param list
     * @return
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<String> writeListObject2Json(List list) throws IOException {
        List<String> objectList = new ArrayList();
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Object o = iter.next();
            String json = objectMapper.writeValueAsString(o);
            objectList.add(json);
        }
        return objectList;
    }

    /**
     * 把List<Object>转换成String[json串]
     *
     * @param list
     * @return
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static String[] writeListObject2ArrayJson(List list) throws IOException {
        if (null == list || list.size() == 0) {
            log.error("class:JsonUtil,method:writeListObject2ArrayJson,param==null");
            return null;
        }
        String[] arrayJson = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            String json = objectMapper.writeValueAsString(o);
            arrayJson[i] = json;
        }
        return arrayJson;
    }

    /**
     * 把map转换成json串
     *
     * @param map
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String writeMap2Json(Map map) {
        try {
            return objectMapper.writeValueAsString(map);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
            return null;
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * JSON字符串转换为对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Object readJson2Entity(String json, Class c) {
        log.debug("class:JsonUtil,method:readJson2Entity,param:json=" + json);
        try {
            return objectMapper.readValue(json, c);
        } catch (JsonParseException e) {
            log.error("class:JsonUtil,method:readJson2Entity", e);
            return null;
        } catch (JsonMappingException e) {
            log.error("class:JsonUtil,method:readJson2Entity", e);
            return null;
        } catch (IOException e) {
            log.error("class:JsonUtil,method:readJson2Entity", e);
            return null;
        }
    }

    /**
     * JSON转换为List对象
     */
    @SuppressWarnings("unchecked")
    public static List<LinkedHashMap<String, Object>> readJson2List(String json) {
        try {
            return objectMapper.readValue(json, List.class);
        } catch (JsonParseException e) {
            e.printStackTrace();
            return null;
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * JSON转换为数组对象
     */
    public static Object[] readJson2Array(String json) {
        try {
            return objectMapper.readValue(json, Object[].class);
        } catch (JsonParseException e) {
            e.printStackTrace();
            return null;
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * JSON转换为Map对象
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Map<String, Object>> readJson2Map(String json) {
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (JsonParseException e) {
            e.printStackTrace();
            return null;
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对象转换字符串
     *
     * @param obj
     * @return
     */
    public static String Object2String(Object obj) {
        String result = null;
        try {
            result = objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换对象
     *
     * @param json
     * @param classObj
     * @return
     */
    public static Object String2Object(String json, Class<?> classObj) {
        Object result = null;
        try {
            result = objectMapper.readValue(json, classObj);
        } catch (Exception e) {
            log.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换Pagination对象,此类有firstIndex":1,"lastIndex":1属性会导致转换异常,过滤这2个属性
     *
     * @param json
     * @param classObj
     * @return
     */
    public static Object String2Pagination(String json, Class<?> classObj) {
        Object result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
            objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            result = objectMapper.readValue(json, classObj);
        } catch (Exception e) {
            log.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换为List<?>
     *
     * @param json
     * @param classObj
     * @return
     */
    public static Object String2List(String json, Class<?> classObj) {
        Object result = null;
        try {
            result = objectMapper.readValue(json, getCollectionType(ArrayList.class, classObj));
        } catch (Exception e) {
            log.error("json转换异常", e);
        }
        return result;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

  }

 

 

 

//json工具类泛型接口

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
  *
 */
public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 对象转换字符串
     *
     * @param obj
     * @return
     */
    public static String Object2String(Object obj) {
        String result = null;
        try {
            result = mapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换对象
     *
     * @param json
     * @param classObj
     * @return
     * @return
     */
    public static <T> T String2Object(String json, Class<T> classObj) {
        T result = null;
        try {
            result = mapper.readValue(json, classObj);
        } catch (Exception e) {
            logger.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换成较复杂的对象,如泛型对象
     *
     * @param json
     * @param classObj
     * @param valueType
     * @return
     */
    public static <T> T String2Object(String json, Class<?> classObj, Class<?>... valueType) {
        T result = null;
        try {
            result = mapper.readValue(json, getCollectionType(classObj, valueType));
        } catch (Exception e) {
            logger.error("json转换异常", e);
        }
        return result;
    }

    /**
     * 字符串转换为List<T>
     *
     * @param json
     * @param classObj
     * @return
     */
    public static <T> List<T> String2List(String json, Class<T> classObj) {
        List<T> result = null;
        try {
            result = mapper.readValue(json, getCollectionType(ArrayList.class, classObj));
        } catch (Exception e) {
            logger.error("json转换异常", e);
        }
        return result;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
}

 

原文链接:https://blog.csdn.net/hjxgood/article/details/20127319
posted on 2024-11-19 16:59  sunny123456  阅读(5)  评论(0编辑  收藏  举报