本文实例讲述了Java实现操作JSON的便捷工具类。分享给大家供大家参考,具体如下:
对于JSON数据格式的处理,自开发Java以来,已用过多种JSON的开源工具,用得最好,也用得最High的恐怕要属Google的Gson了。
特别为它写了一个工具类,放入常备工具中,方便使用。下面是为GSON 1.5版本重写的工具类。
依赖包:
slf4j-api-1.6.0.jar
slf4j-log4j12-1.6.0.jar
log4j-1.2.15.jar
gson-1.5.jar
package my.tools;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.StringUtils;
public class JSonUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);
public static final String EMPTY_JSON = "{}";
public static final String EMPTY_JSON_ARRAY = "[]";
public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS";
public static final double SINCE_VERSION_10 = 1.0d;
public static final double SINCE_VERSION_11 = 1.1d;
public static final double SINCE_VERSION_12 = 1.2d;
public static final double UNTIL_VERSION_10 = SINCE_VERSION_10;
public static final double UNTIL_VERSION_11 = SINCE_VERSION_11;
public static final double UNTIL_VERSION_12 = SINCE_VERSION_12;
public JSonUtils() {
super();
}
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
String datePattern, boolean excludesFieldsWithoutExpose) {
if (target == null) return EMPTY_JSON;
GsonBuilder builder = new GsonBuilder();
if (isSerializeNulls) builder.serializeNulls();
if (version != null) builder.setVersion(version.doublevalue());
if (StringUtils.isBlank(datePattern)) datePattern = DEFAULT_DATE_PATTERN;
builder.setDateFormat(datePattern);
if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation();
return toJson(target, targetType, builder);
}
public static String toJson(Object target) {
return toJson(target, null, false, null, null, true);
}
public static String toJson(Object target, String datePattern) {
return toJson(target, null, false, null, datePattern, true);
}
public static String toJson(Object target, Double version) {
return toJson(target, null, false, version, null, true);
}
public static String toJson(Object target, boolean excludesFieldsWithoutExpose) {
return toJson(target, null, false, null, null, excludesFieldsWithoutExpose);
}
public static String toJson(Object target, Double version, boolean excludesFieldsWithoutExpose) {
return toJson(target, null, false, version, null, excludesFieldsWithoutExpose);
}
public static String toJson(Object target, Type targetType) {
return toJson(target, targetType, false, null, null, true);
}
public static String toJson(Object target, Type targetType, Double version) {
return toJson(target, targetType, false, version, null, true);
}
public static String toJson(Object target, Type targetType, boolean excludesFieldsWithoutExpose) {
return toJson(target, targetType, false, null, null, excludesFieldsWithoutExpose);
}
public static String toJson(Object target, Type targetType, Double version, boolean excludesFieldsWithoutExpose) {
return toJson(target, targetType, false, version, null, excludesFieldsWithoutExpose);
}
public static T fromJson(String json, TypeToken token, String datePattern) {
if (StringUtils.isBlank(json)) {
return null;
}
GsonBuilder builder = new GsonBuilder();
if (StringUtils.isBlank(datePattern)) {
datePattern = DEFAULT_DATE_PATTERN;
}
Gson gson = builder.create();
try {
return gson.fromJson(json, token.getType());
} catch (Exception ex) {
LOGGER.error(json + " 无法转换为 " + token.getRawType().getName() + " 对象!", ex);
return null;
}
}
public static T fromJson(String json, TypeToken token) {
return fromJson(json, token, null);
}
public static T fromJson(String json, Class clazz, String datePattern) {
if (StringUtils.isBlank(json)) {
return null;
}
GsonBuilder builder = new GsonBuilder();
if (StringUtils.isBlank(datePattern)) {
datePattern = DEFAULT_DATE_PATTERN;
}
Gson gson = builder.create();
try {
return gson.fromJson(json, clazz);
} catch (Exception ex) {
LOGGER.error(json + " 无法转换为 " + clazz.getName() + " 对象!", ex);
return null;
}
}
public static T fromJson(String json, Class clazz) {
return fromJson(json, clazz, null);
}
public static String toJson(Object target, Type targetType, GsonBuilder builder) {
if (target == null) return EMPTY_JSON;
Gson gson = null;
if (builder == null) {
gson = new Gson();
} else {
gson = builder.create();
}
String result = EMPTY_JSON;
try {
if (targetType == null) {
result = gson.toJson(target);
} else {
result = gson.toJson(target, targetType);
}
} catch (Exception ex) {
LOGGER.warn("目标对象 " + target.getClass().getName() + " 转换 JSON 字符串时,发生异常!", ex);
if (target instanceof Collection> || target instanceof Iterator> || target instanceof Enumeration>
|| target.getClass().isArray()) {
result = EMPTY_JSON_ARRAY;
}
}
return result;
}
}
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
更多关于java相关内容感兴趣的读者可查看本站专题:《Java操作json格式数据技巧总结》、《Java数组操作技巧总结》、《Java字符与字符串操作技巧总结》、《Java数学运算技巧总结》、《Java数据结构与算法教程》及《Java操作DOM节点技巧总结》
希望本文所述对大家java程序设计有所帮助。



