json common jackson
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper ( ) ;
private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss" ;
static {
OBJECT_MAPPER. setSerializationInclusion ( JsonInclude. Include. ALWAYS) ;
OBJECT_MAPPER. configure ( SerializationFeature. WRITE_DATES_AS_TIMESTAMPS, false ) ;
OBJECT_MAPPER. configure ( SerializationFeature. FAIL_ON_EMPTY_BEANS, false ) ;
OBJECT_MAPPER. setDateFormat ( new SimpleDateFormat ( STANDARD_FORMAT) ) ;
OBJECT_MAPPER. configure ( DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false ) ;
}
public static < T> String obj2String ( T obj) {
if ( obj == null) {
return null;
}
try {
return OBJECT_MAPPER. writeValueAsString ( obj) ;
} catch ( JsonProcessingException e) {
e. printStackTrace ( ) ;
}
return null;
}
public static < T> String obj2StringPretty ( T obj) {
if ( obj == null) {
return null;
}
try {
return OBJECT_MAPPER. writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( obj) ;
} catch ( JsonProcessingException e) {
e. printStackTrace ( ) ;
}
return null;
}
public static < T> T string2Obj ( String str, Class< T> clazz) {
if ( StringUtils. isEmpty ( str) || clazz == null) {
return null;
}
try {
return OBJECT_MAPPER. readValue ( str, clazz) ;
} catch ( JsonProcessingException e) {
e. printStackTrace ( ) ;
}
return null;
}
public static < T> List< T> string2List ( String str) {
if ( StringUtils. isEmpty ( str) ) {
return null;
}
TypeReference< List< T> > typeReference = new TypeReference < List< T> > ( ) {
} ;
return string2Obj ( str, typeReference) ;
}
public static Map< Object, Object> string2Map ( String str) {
if ( StringUtils. isEmpty ( str) ) {
return null;
}
TypeReference< Map< Object, Object> > typeReference = new TypeReference < Map< Object, Object> > ( ) {
} ;
return string2Obj ( str, typeReference) ;
}
public static < T> T string2Obj ( String str, TypeReference< T> tTypeReference) {
if ( StringUtils. isEmpty ( str) ) {
return null;
}
try {
return OBJECT_MAPPER. readValue ( str, tTypeReference) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
return null;
}
}