依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
JsonUtils.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class JsonUtils {
private final static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
private static SerializeConfig config;
static {
config = new SerializeConfig();
}
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 JSONObject toJSONObject(String text) {
try {
return JSON.parseObject(text);
} catch (Exception e) {
logger.error("JsonUtil | method=toJSON() | 将json格式的数据换为JSONObject 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 (json == null || key == null) {
return null;
}
return JSON.parseObject(json).getString(key);
} catch (Exception e) {
logger.error("JsonUtil | method=getStringFromJson() | 从json获取指定key的字符串 Error!" + e.getMessage(), e);
}
return null;
}
}