com.neusoft.mid.clwapi.tools.JacksonUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.neusoft.mid.clwapi.tools.JacksonUtils.java

Source

/**
 * @(#)JacksonUtils.java 2013-3-25
 *
 * Copyright 2013 Neusoft Group Ltd. All rights reserved.
 * Neusoft PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.neusoft.mid.clwapi.tools;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import com.neusoft.mid.clwapi.exception.common.JacksonDeserializeException;
import com.neusoft.mid.clwapi.exception.common.JacksonSerializeException;

/**
 * @author <a href="mailto:yi_liu@neusoft.com">yi_liu </a>
 * @version $Revision 1.0 $ 2013-3-25 ?4:12:58
 */
public class JacksonUtils {

    private static Logger logger = LoggerFactory.getLogger(JacksonUtils.class);
    /**
     * jackson
     */
    private static ObjectMapper iMapper = new ObjectMapper();

    private static String[] DECODER_CHAR = new String[] { "\b", "\t", "\n", "\f", "\r", "\"", "\\" };
    private static String[] ENCODER_CHAR = new String[] { "\\b", "\\t", "\\n", "\\f", "\\r", "\\\"", "\\\\" };

    /**
     * ????? {@code JSON} ?
     * 
     * @param obj
     *            
     * @return  {@code JSON} ?
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static String toJson(Object obj) throws IOException {
        return iMapper.writeValueAsString(obj);
    }

    /**
     *  {@code JSON} ??<strong>?? {@code JavaBean}
     * </strong>
     * 
     * @param json
     *             {@code JSON} 
     * @param clz
     *            ??
     * @return  {@code JSON} 
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws BeanUtilException
     */
    public static <T> T fromJson(String json, Class<T> clz) throws IOException {
        T o = iMapper.readValue(json, clz);
        return o;
    }

    /**
     * ????? {@code JSON} ?
     * ?????
     * 
     * @param obj
     *            
     * @return  {@code JSON} ?
     */
    public static String toJsonRuntimeException(Object obj) {
        String str = new String();
        try {
            str = iMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new JacksonSerializeException(e);
        }
        return str;
    }

    /**
     *  {@code JSON} ??<strong>?? {@code JavaBean}
     * </strong> ?????
     * 
     * @param json
     *             {@code JSON} 
     * @param clz
     *            ??
     * @return  {@code JSON} 
     */
    public static <T> T fromJsonRuntimeException(String json, Class<T> clz) {
        T t = null;
        try {
            t = iMapper.readValue(json, clz);
        } catch (Exception e) {
            throw new JacksonDeserializeException(e);
        }
        return t;
    }

    /**
     * json???map
     * 
     * @param jsonStr
     *             {@code JSON} 
     * @return objMap ??MAP
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws BeanUtilException
     */
    public static Map<?, ?> jsonToMap(String json) throws IOException {
        Map<?, ?> o = iMapper.readValue(json, Map.class);
        return o;
    }

    /**
     * json???map
     * 
     * @param jsonStr
     *             {@code JSON} 
     * @return objMap ??MAP
     */
    public static Map<?, ?> jsonToMapRuntimeException(String json) {
        try {
            Map<?, ?> o = iMapper.readValue(json, Map.class);
            return o;
        } catch (Exception e) {
            throw new JacksonDeserializeException(e);
        }
    }

    /**
     * json???list
     * 
     * @param jsonStr
     *             {@code JSON} 
     * @return objList ??LIST
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws BeanUtilException
     */
    public static List<?> jsonToList(String json) throws IOException {
        List<?> o = iMapper.readValue(json, List.class);
        return o;
    }

    /**
     * json???list
     * 
     * @param jsonStr
     *             {@code JSON} 
     * @return objList ??LIST
     */
    public static List<?> jsonToListRuntimeException(String json) {
        try {
            List<?> o = iMapper.readValue(json, List.class);
            return o;
        } catch (Exception e) {
            throw new JacksonDeserializeException(e);
        }
    }

    /**
     * String?
     * 
     * @param obj
     *            ?(?JavaBean,String,Collection,Map)
     * @return ??
     * @throws JacksonEncoderException
     *             jackson?
     */
    public static Object jsonEncoder(Object obj) throws JacksonEncoderException {
        logger.debug("obj class is:" + obj.getClass());
        if (obj instanceof String) {
            return jsonCoder((String) obj, true);
        } else if (obj instanceof Map<?, ?>) {
            logger.debug("Object is " + obj.getClass());
            Set<?> entries = ((Map<?, ?>) obj).entrySet();
            Iterator<?> it = entries.iterator();
            while (it.hasNext()) {
                Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
                logger.debug("Key is [" + entry.getKey() + "]");
                entry.setValue(jsonEncoder(entry.getValue()));
            }
        } else if (obj instanceof Collection<?>) {
            logger.debug("Object is " + obj.getClass());
            Collection<?> c = (Collection<?>) obj;
            Iterator<?> it = c.iterator();
            while (it.hasNext()) {
                jsonEncoder(it.next());
            }
        } else {
            try {
                Field[] fields = obj.getClass().getFields();
                for (Field f : fields) {
                    jsonCoder(obj, f);
                }
            } catch (IllegalAccessException e) {
                logger.error("json??" + e.getMessage());
                throw new JacksonEncoderException(e);
            }
        }
        return obj;
    }

    /**
     * @param obj
     * @param f
     * @throws IllegalAccessException
     * @throws JacksonEncoderException
     */
    private static Object jsonCoder(Object obj, Field f) throws IllegalAccessException, JacksonEncoderException {
        Object o = FieldUtils.readField(f, obj);
        if (o instanceof String) {
            FieldUtils.writeField(f, obj, jsonCoder((String) o, true));
        } else if (o instanceof Collection<?>) {
            logger.debug("Field [" + f.getName() + "] is " + o.getClass());
            Collection<?> c = (Collection<?>) o;
            Iterator<?> it = c.iterator();
            while (it.hasNext()) {
                jsonEncoder(it.next());
            }
        } else if (o instanceof Map<?, ?>) {
            logger.debug("Field [" + f.getName() + "] is " + o.getClass());
            Set<?> entries = ((Map<?, ?>) o).entrySet();
            Iterator<?> it = entries.iterator();
            while (it.hasNext()) {
                Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
                logger.debug("Key is [" + entry.getKey() + "]");
                entry.setValue(jsonEncoder(entry.getValue()));
            }
        } else if (o instanceof Integer || o instanceof Byte || o instanceof Boolean || o instanceof Long
                || o instanceof Double || o instanceof Character || o instanceof Short || o instanceof Float
                || o instanceof Number) {
            return obj;
        } else {
            throw new JacksonEncoderException("??" + f.getClass());
        }
        return obj;
    }

    /**
     * json</br>
     * 
     * JacksonUtils.jsonCoder(null,true) = null;
     * JacksonUtils.jsonCoder(null,false) = null;
     * JacksonUtils.jsonCoder("\babc\t\"",true) = "\\babc\\t\\\"";
     * JacksonUtils.jsonCoder("\\babc\\t\\\"",false) = "\babc\t\"";
     * 
     * @param str
     * @param encoder
     * @return
     */
    private static String jsonCoder(String str, boolean encoder) {
        logger.debug("transferred meaning value is [" + str + "]");
        String newStr = null;
        if (encoder) {
            // encoder
            newStr = StringUtils.replaceEach(str, DECODER_CHAR, ENCODER_CHAR);
        } else {
            // decoder
            newStr = StringUtils.replaceEach(str, ENCODER_CHAR, DECODER_CHAR);
        }
        logger.debug("transferred meaned value is  [" + newStr + "]");
        return newStr;
    }

    /**
     * ?jackson
     */
    static {
        // ?????private
        iMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        Logger logger = LoggerFactory.getLogger(JacksonUtils.class);
        // Debug??
        if (logger.isErrorEnabled()) {
            // ?
            iMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        }
        // null?
        iMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // ?Jaxb
        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
        AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
        AnnotationIntrospectorPair pair = new AnnotationIntrospectorPair(introspector, primary);
        iMapper.setAnnotationIntrospector(pair);
    }
}