標籤:exce val string class for classes json log lse
1. JsonUtil
通過 jackson包提供的方法 實現一個字串轉對象,對象轉字串的類,使用情境,redis實現單點登陸
package com.mmall.util;import com.google.common.collect.Lists;import com.mmall.pojo.Category;import com.mmall.pojo.TestPojo;import com.mmall.pojo.User;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang.StringUtils;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.JavaType;import org.codehaus.jackson.type.TypeReference;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by geely */@Slf4jpublic class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); static{ //對象的所有欄位全部列入 objectMapper.setSerializationInclusion(Inclusion.ALWAYS); //取消預設轉換timestamps形式 objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false); //忽略空Bean轉json的錯誤 objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false); //所有的日期格式都統一為以下的樣式,即yyyy-MM-dd HH:mm:ss objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT)); //忽略 在json字串中存在,但是在java對象中不存在對應屬性的情況。防止錯誤 objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false); } public static <T> String obj2String(T obj){ if(obj == null){ return null; } try { return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj); } catch (Exception e) { log.warn("Parse Object to String error",e); return null; } } public static <T> String obj2StringPretty(T obj){ if(obj == null){ return null; } try { return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (Exception e) { log.warn("Parse Object to String error",e); return null; } } public static <T> T string2Obj(String str,Class<T> clazz){ if(StringUtils.isEmpty(str) || clazz == null){ return null; } try { return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz); } catch (Exception e) { log.warn("Parse String to Object error",e); return null; } } public static <T> T string2Obj(String str, TypeReference<T> typeReference){ if(StringUtils.isEmpty(str) || typeReference == null){ return null; } try { return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference)); } catch (Exception e) { log.warn("Parse String to Object error",e); return null; } } public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){ JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses); try { return objectMapper.readValue(str,javaType); } catch (Exception e) { log.warn("Parse String to Object error",e); return null; } }}
Java web 開發中幾個高可複用的類