Json操作工具类,使用jackson,可用作json字符串转Java类,字符串转Map,Java对象转json字符串等等.md
一、Json工具类如下
package cn.lihua.system.utils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
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.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
public class JsonUtil {
private final static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static ObjectMapper objectMapper;
static{
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
JavaTimeModule module=new JavaTimeModule();
module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
objectMapper.registerModule(module);
}
public static String toJSONString(Object o) {
if (o == null) {
return null;
}
if (o instanceof String)
return (String) o;
String jsonValue = null;
try {
jsonValue = objectMapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
logger.error("Parse Object to String error",e);
}
return jsonValue;
}
@SuppressWarnings("unchecked")
public static Map<String,Object> castToObject(String fromValue){
if(fromValue == null || "".equals(fromValue) ){
return null;
}
try {
return objectMapper.readValue(fromValue, Map.class);
} catch (Exception e) {
logger.error("Parse String to Object error:", e);
return null;
}
}
@SuppressWarnings("unchecked")
public static <T> T castToObject(String fromValue, Class<T> clazz){
if(fromValue == null || "".equals(fromValue) || clazz == null){
return null;
}
try {
return clazz.equals(String.class) ? (T) fromValue : objectMapper.readValue(fromValue, clazz);
} catch (Exception e) {
logger.error("Parse String to Object error:", e);
return null;
}
}
@SuppressWarnings("unchecked")
public static <T> T castToObject(String fromValue, TypeReference<T> typeReference) {
if (fromValue == null || "".equals(fromValue) || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? fromValue : objectMapper.readValue(fromValue, typeReference));
} catch (IOException e) {
logger.error("Parse String to Object error:", e);
return null;
}
}
public static <T> T castToObject(String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
try {
return objectMapper.readValue(fromValue, javaType);
} catch (IOException e) {
logger.error("Parse String to Object error : ", e.getMessage());
return null;
}
}
public static <T> T getValue(String fromValue, Class<T> clazz){
return castToObject(fromValue,clazz);
}
public static <T> T getValue(String fromValue, TypeReference<T> toValueTypeRef){
return castToObject(fromValue, toValueTypeRef);
}
public static <T> T getValue(String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes){
return castToObject(fromValue, collectionClazz, elementClazzes);
}
public static <T> T getValue(String key, String fromValue, Class<T> clazz){
Map<String,Object> infoMap = castToObject(fromValue);
if(infoMap == null) return null;
return getValue(key, infoMap, clazz);
}
public static <T> T getValue(String key, String fromValue, TypeReference<T> toValueTypeRef){
Map<String,Object> infoMap = castToObject(fromValue);
if(infoMap == null) return null;
return getValue(key, infoMap, toValueTypeRef);
}
public static <T> T getValue(String key, String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes){
Map<String,Object> infoMap = castToObject(fromValue);
if(infoMap == null) return null;
return getValue(key, infoMap, collectionClazz, elementClazzes);
}
@SuppressWarnings("rawtypes")
public static <T> T getValue(String key, Map fromMap, Class<T> clazz){
try {
String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]);
if(value == null) return null;
if (i < keys.length - 1) {
fromMap = (Map) value;
}else {
return objectMapper.convertValue(value, clazz);
}
}
} catch (Exception e) {
logger.error("getValue error : ", e.getMessage());
return null;
}
return null;
}
@SuppressWarnings("rawtypes")
public static <T> T getValue(String key, Map fromMap, Class<?> collectionClazz, Class<?>... elementClazzes){
try {
String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]);
if(value == null) return null;
if (i < keys.length - 1) {
fromMap = (Map) value;
}else {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
return objectMapper.convertValue(value, javaType);
}
}
} catch (Exception e) {
logger.error("getValue error : ", e.getMessage());
return null;
}
return null;
}
@SuppressWarnings("rawtypes")
public static <T> T getValue(String key, Map fromMap, TypeReference<T> toValueTypeRef){
try {
String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]);
if(value == null) return null;
if (i < keys.length - 1) {
fromMap = (Map) value;
}else {
return objectMapper.convertValue(value, toValueTypeRef);
}
}
} catch (Exception e) {
logger.error("getValue error : ", e.getMessage());
return null;
}
return null;
}
public static <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef){
try {
return objectMapper.convertValue(fromValue, toValueTypeRef);
} catch (Exception e) {
logger.error("convertValue error : ", e.getMessage());
return null;
}
}
public static <T> T convertValue(Object fromValue, Class<T> toValueType){
try {
return objectMapper.convertValue(fromValue, toValueType);
} catch (Exception e) {
logger.error("convertValue error : ", e.getMessage());
return null;
}
}
public static String getString(Map<String,Object> fromMap, String fieldName){
return fromMap.get(fieldName)==null ? null : fromMap.get(fieldName).toString();
}
public static String getString(Map<String,Object> jsonObject, String fieldName,String defaultValue){
return jsonObject.get(fieldName)==null ? defaultValue : jsonObject.get(fieldName).toString();
}
public static Integer getInteger(Map<String,Object> jsonObject, String fieldName){
return jsonObject.get(fieldName)==null ? null : (Integer)jsonObject.get(fieldName);
}
public static Double getDouble(Map<String,Object> jsonObject, String fieldName){
return jsonObject.get(fieldName)==null ? null : (Double)jsonObject.get(fieldName);
}
public static Boolean getBoolean(Map<String,Object> jsonObject, String fieldName){
return jsonObject.get(fieldName)==null ? false : (Boolean)jsonObject.get(fieldName);
}
public static Long getLong(Map<String,Object> jsonObject, String fieldName){
return jsonObject.get(fieldName)==null ? null : (Long)jsonObject.get(fieldName);
}
@SuppressWarnings("unchecked")
public static <T> List<T> getList(Map<String,Object> jsonObject, String fieldName,Class<T> clazz){
return jsonObject.get(fieldName)==null ? null : (List<T>)jsonObject.get(fieldName);
}
@SuppressWarnings("unchecked")
public static <T> T[] getArray(Map<String,Object> jsonObject, String fieldName,Class<T> clazz){
return jsonObject.get(fieldName)==null ? null : (T[])jsonObject.get(fieldName);
}
}
二、测试
UserList info = new UserList();
info.setUuid(java.util.UUID.randomUUID().toString());
info.setAge(100);
User user1 = new User();
user1.setUser("liu");
user1.setAge(40);
user1.setCurrentTime(LocalDateTime.now());
user1.setDateTime(new Date());
User user2 = new User();
user2.setUser("he");
user2.setAge(35);
user2.setCurrentTime(LocalDateTime.now());
user2.setDateTime(new Date());
List<User> list1 = new ArrayList<User>();
list1.add(user1);
list1.add(user2);
Set<User> sets = new HashSet<User>();
sets.add(user1);
info.setSubUsers(list1);
info.setSubSets(sets);
Map<String,Object> result = new LinkedHashMap<String, Object>();
result.put("success", true);
result.put("code", 200);
result.put("data", info);
String jsonStr = JsonUtil.toJSONString(result);
System.out.println(jsonStr);
Map<String,Object> mapInfo = JsonUtil.castToObject(jsonStr);
UserList userList = JsonUtil.getValue("data", jsonStr, UserList.class);
System.out.println(userList);
System.out.println(JsonUtil.getValue("data", jsonStr, Map.class));
System.out.println(JsonUtil.getValue("data.uuid", jsonStr, String.class));
System.out.println(JsonUtil.getValue("data.uuid", mapInfo, String.class));
System.out.println(JsonUtil.getValue("data.age", jsonStr, Integer.class));
System.out.println(JsonUtil.getValue("data.age", mapInfo, Integer.class));
List<User> list11 = JsonUtil.getValue("data.subUsers", jsonStr, List.class, User.class);
System.out.println("list11:" + list11);
System.out.println(JsonUtil.getValue("data.subUsers", jsonStr, new TypeReference<List<User>>(){} ).getClass());
System.out.println(JsonUtil.getValue("data.subUsers", mapInfo, new TypeReference<List<User>>(){} ).getClass());
System.out.println(JsonUtil.getValue("data.subUsers", mapInfo, List.class ).getClass());
Set<User> set11 = JsonUtil.getValue("data.subSets", jsonStr, Set.class, User.class);
System.out.println("set11:" + set11);
System.out.println(JsonUtil.getValue("data.subSets", jsonStr, new TypeReference<Set<User>>(){} ).getClass());
System.out.println(JsonUtil.getValue("data.subSets", mapInfo, new TypeReference<Set<User>>(){} ).getClass());
String setStr = JsonUtil.toJSONString(JsonUtil.getValue("data.subSets", jsonStr, List.class));
System.out.println("setStr: " + setStr);
System.out.println(JsonUtil.castToObject(setStr, new TypeReference<Set<User>>(){} ));
System.out.println(JsonUtil.toJSONString(list1));
List<User> list = JsonUtil.castToObject(JsonUtil.toJSONString(list1),List.class, User.class);
System.out.println(list);
System.out.println(JsonUtil.getValue("data", jsonStr, UserList.class));