基于fastjson的json工具类
package com.abc.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class JsonUtil {
private final static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static SerializeConfig config;
static {
config = new SerializeConfig();
config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
}
private static final SerializerFeature[] features = {
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullStringAsEmpty
};
public static String toJSON(Object object) {
try {
return JSON.toJSONString(object, config, features);
} catch (Exception e) {
logger.error("JsonUtil | method=toJSON() | 对象转为Json字符串 Error!" + e.getMessage(), e);
}
return null;
}
public static String toJSONLib(Object object) {
try {
return JSON.toJSONString(object, config, features);
} catch (Exception e) {
logger.error("JsonUtil | method=toJSONLib() | 对象转为Json字符串 Json-lib兼容的日期输出格式 Error!" + e.getMessage(), e);
}
return null;
}
public static Object[] toArray(String text) {
try {
return toArray(text, null);
} catch (Exception e) {
logger.error("JsonUtil | method=toArray() | 将json格式的数据转换为数组 Object Error!" + e.getMessage(), e);
}
return null;
}
public static <T> Object[] toArray(String text, Class<T> clazz) {
try {
return JSON.parseArray(text, clazz).toArray();
} catch (Exception e) {
logger.error("JsonUtil | method=toArray() | 将json格式的数据转换为数组 (可指定类型) Error!" + e.getMessage(), e);
}
return null;
}
public static <T> T toBean(String text, Class<T> clazz) {
try {
return JSON.parseObject(text, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=toBean() | Json 转为 Jave Bean Error!" + e.getMessage(), e);
}
return null;
}
public static Map<?, ?> toMap(String json) {
try {
return JSON.parseObject(json);
} catch (Exception e) {
logger.error("JsonUtil | method=toMap() | Json 转为 Map {},{}" + e.getMessage(), e);
}
return null;
}
public static <T> List<T> toList(String text, Class<T> clazz) {
try {
return JSON.parseArray(text, clazz);
} catch (Exception e) {
logger.error("JsonUtil | method=toList() | Json 转为 List {},{}" + e.getMessage(), e);
}
return null;
}
public static Object getValueFromJson(final String json, final String key) {
try {
if (StringUtil.isBlank(json) || StringUtil.isBlank(key)) {
return null;
}
return JSON.parseObject(json).getString(key);
} catch (Exception e) {
logger.error("JsonUtil | method=getStringFromJson() | 从json获取指定key的字符串 Error!" + e.getMessage(), e);
}
return null;
}
}
End