JsonUtils

功能:

  • json2Bean 将JSON序列化为对象
  • bean2Json 将对象序列化为JSON
  • bean2Bytes 将对象序列化为字节流
依赖:


      org.codehaus.jackson
      jackson-mapper-asl
      1.9.9

源码:

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Dotions 2016年4月26日下午5:33:55
 */
public class JsonUtils {
    
    private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    
    private static ObjectMapper objectMapper;
    
    //init objectMapper
    static {
        objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
        objectMapper.disable(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES);
    }
    
    public static  T json2Bean(String json, Class clazz) throws Exception {
        try {
            return objectMapper.readValue(json, clazz);
        } catch(Exception e) {
            logger.error("convert json to bean failed", e);
            throw e;
        }
    }
    
    /**
     * ex:List list = JsonUtils.json2Bean(listJson, new TypeReference>() {}) ;
     * use to convert Collection
     */
    public static  T json2Bean(String json, TypeReference typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            logger.error("convert json to bean failed", e);
            return null;
        }
    }
    
    public static String bean2Json(Object bean) throws Exception {
        try {
            return objectMapper.writeValueAsString(bean);
        } catch (Exception e) {
            logger.error("convert bean to json failed", e);
            throw e;
        }
    }
    
    public static byte[] bean2Bytes(Object bean) throws Exception {
        try {
            return objectMapper.writeValueAsBytes(bean);
        } catch (Exception e) {
            logger.error("convert bean to json bytes failed", e);
            throw e;
        }
    }
    
}

你可能感兴趣的:(JsonUtils)