package com.jfai.kg.util;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName: GsonUtil.java
* @Package com.jf.util
* @author wanglf
* @Description: GsonUtil 工具类
* @date 2018年6月7日 下午5:58:40
* @version 1.3.3
* @remark
* 替换了默认的gson对象,消除神奇的/u003d 转义问题 2018年7月1日12:00:59
* 略微增强了GsonUtil的功能.. 2018年7月7日14:41:55
* 新增ResultSet 转JsonObject,转JsonObjectList和转json字符串功能 2018年7月13日14:41:49
* 类功能增强 2018年7月19日17:15:49
* 调整ResultSet处理方法 2018年7月22日22:45:52
* 新增json字符串合法性校验 2018年7月29日11:07:52
* 注释更新 2018年8月5日13:20:29
* 将原先使用的HashMap全部更换成LinkedHashMap 2018年8月14日11:11:31
*/
@Slf4j
public final class GsonUtil {
public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private GsonUtil() {
}
/**
* 获得 GsonUtil 默认的内置Gson 对象
* @return Gson
*/
public static Gson getGson() {
return gson;
}
/**
* json字符串转成对象
* @param str
* @param type
* @return
*/
public static Object fromJsonToObject(String str, Type type) {
try {
return gson.fromJson(str, type);
} catch (Exception e) {
log.error("Exception :", e);
}
return null;
}
/**
* json字符串转成对象
* @param str
* @param type
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object fromJsonToObject(String str, Class clazz) {
try {
return gson.fromJson(str, clazz);
} catch (Exception e) {
log.error("Exception :", e);
}
return null;
}
/**
* 验证一个字符串是否是合法的JSON串
*
* @param json 要验证的字符串
* @return true-合法 ,false-非法
*/
public static boolean isJSON(String json) {
try {
gson.fromJson(json, Object.class);
return true;
} catch (JsonSyntaxException ex) {
return false;
}
}
/**
* 是否是合法的Gson字符串
* @param targetStr
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static boolean isGoodGson(String targetStr, Class clazz) {
try {
gson.fromJson(targetStr, clazz);
return true;
} catch (JsonSyntaxException ex) {
log.error("targetStr={} is not a valid {}", targetStr, clazz.getName(), ex);
return false;
}
}
/**
* 是否是合法的JsonArray (alibaba 认为前1种不是JSON串)
* 例如:[{a:b}] [{'a':'b'}] [{"a":"b"}]
* @param targetStr
* @return
*/
public static boolean isJsonArray(String targetStr) {
return isGoodGson(targetStr, JsonArray.class);
}
/**
* 是否是合法的JsonObject(alibaba 认为前1种不是JSON串)
* 例如:{a:b} {'a':'b'} {"a":"b"}
* @param targetStr
* @return
*/
public static boolean isJsonObject(String targetStr) {
return isGoodGson(targetStr, JsonObject.class);
}
/**
* json转List
* */
// private void test(){
// String json = "";
// String result = gson.fromJson(json,new TypeToken<List<Object>>()
// {}.getType());//转换为集合
// }
private static Map<String, Object> jsonMap = new LinkedHashMap<String, Object>();
/**
* 获取JsonObject
* @param json
* @return
*/
public static JsonObject parseJson(String json) {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(json).getAsJsonObject();
return jsonObj;
}
/**
* 获取json节点数据
* @param element
* @param json字符串
* @return
*/
public static String getString(String element, String json) {
JsonParser parser = new JsonParser();
String re = "";
try {
re = parser.parse(json).getAsJsonObject().get(element).getAsString();
} catch (JsonSyntaxException e) {
return "";
}
return re;
}
/**
* 判断 jsonObject,该key对应的value是否有值
* @param key
* @param jsonObject
* @return
* @Description: 该函数的功能描述
*/
public static boolean isHasValue(String key, JsonObject jsonObject) {
if (jsonObject == null || jsonObject.size() == 0 || jsonObject.isJsonNull()) {
return false;
}
if (jsonObject.get(key) != null && jsonObject.get(key).toString().trim().length() != 0) {
return true;
}
return false;
}
/**
* 依据key,获取jsonObject数据
* @param jsonObject
* @param element
* @return element's value or ""
*/
public static String getString(String element, JsonObject jsonObject) {
String re = "";
try {
if (jsonObject.has(element) && jsonObject.get(element) != null && !(jsonObject.get(element) instanceof JsonNull)) {
re = jsonObject.get(element).getAsString();
}
} catch (JsonSyntaxException e) {
return "";
} catch (Exception e) {
log.error("GsonUtil.getString Exception :", e);
return "";
}
return re;
}
/**
* 依据key,获取jsonObject数据
* @param jsonObject
* @param element
* @return
*/
public static Integer getInteger(String element, JsonObject jsonObject) {
Integer i = null;
try {
// getAsInt 内置Integer.parseInt
i = jsonObject.get(element).getAsInt();
} catch (JsonSyntaxException e) {
} catch (NumberFormatException e) {
} catch (UnsupportedOperationException e) {
} catch (Exception e) {
}
return i;
}
/**
* 依据key,以Long的形式获取jsonObject的数据
*/
public static Long getLong(String element, JsonObject jsonObject) {
Long i = null;
try {
// i = jsonObject.get(element).getAsLong();
i = Long.parseLong(getString(element, jsonObject).trim());
} catch (JsonSyntaxException e) {
} catch (NumberFormatException e) {
} catch (Exception e) {
}
return i;
}
/**
* 根据json字符串返回Map对象
* @param json
* @return
*/
public static Map<String, Object> toMap(String json) {
return GsonUtil.toMap(GsonUtil.parseJson(json));
}
/**
* 按照key值的ASCII大小升序排列
* @param json
* @return
*/
public static Map<String, Object> JsonOrderByAscii(String json) {
return GsonUtil.JsonOrderByAscii(GsonUtil.parseJson(json));
}
/**
* 解析json字符串,并按照key值的ASCII码大小排序
* @param json
* @return
*/
public static Map<String, Object> JsonOrderByAscii(JsonObject json) {
Map<String, Object> map = new TreeMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = json.entrySet();
for (Iterator<Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext();) {
Entry<String, JsonElement> entry = iter.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if (value instanceof JsonArray) {
map.put((String) key, toList((JsonArray) value));
} else if (value instanceof JsonObject) {
map.put((String) key, JsonOrderByAscii((JsonObject) value));
} else {
if (value.toString().indexOf("\"") > -1) {
map.put((String) key, value.getAsString());
} else {
map.put((String) key, value);
}
}
}
return map;
}
/**
* 将JSONObjec对象转换成Map-List集合
* @param json
* @return
*/
public static Map<String, Object> toMap(JsonObject json) {
Set<Entry<String, JsonElement>> entrySet = json.entrySet();
for (Iterator<Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext();) {
Entry<String, JsonElement> entry = iter.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if (value instanceof JsonArray) {
tojsonList((JsonArray) value);
} else if (value instanceof JsonObject) {
toMap((JsonObject) value);
} else {
if (value.toString().indexOf("\"") > -1) {
jsonMap.put((String) key, value.getAsString());
} else {
jsonMap.put((String) key, value);
}
}
}
return jsonMap;
}
/**
* 将JSONArray对象转换成List集合
* @param json
* @return
*/
public static List<Object> toList(JsonArray json) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < json.size(); i++) {
Object value = json.get(i);
if (value instanceof JsonArray) {
list.add(toList((JsonArray) value));
} else if (value instanceof JsonObject) {
list.add(JsonOrderByAscii((JsonObject) value));
} else {
list.add(value);
}
}
return list;
}
/**
* 将JSONArray对象转换成List集合
* @param json
* @return
*/
public static List<Object> tojsonList(JsonArray json) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < json.size(); i++) {
Object value = json.get(i);
if (value instanceof JsonArray) {
tojsonList((JsonArray) value);
} else if (value instanceof JsonObject) {
toMap((JsonObject) value);
}
}
return list;
}
/*
* 将字符串转换成JsonArray
*/
public static JsonArray toJsonArray(String str) {
// 创建一个JsonParser
JsonParser parser = new JsonParser();
// 通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
JsonElement el = parser.parse(str);
// 把JsonElement对象转换成JsonArray
JsonArray jsonArray = null;
if (el.isJsonArray()) {
jsonArray = el.getAsJsonArray();
}
return jsonArray;
}
/**
* 对象转换成json字符串
* @param obj
* @return
*/
public static String toJson(Object obj) {
if (obj == null) {
return "";
}
return gson.toJson(obj);
}
/**
* key value String Object 对象转换成 相应的map json字符串
* @param obj
* @return
*/
public static String toJson(String key, Object obj) {
try {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put(key, obj);
return gson.toJson(map);
} catch (Exception e) {
log.error("Exception :", e);
}
return null;
}
/**
* 反序列化对象
*
* @param json
* @param clazz
* @return
*/
public static <T> T fromJson(String json, Class<T> clazz) {
return gson.fromJson(json, clazz);
}
/**
* 反序列化对象
*
* @param json
* @param type
* @return
*/
public static Object fromJson(String json, Type type) {
return gson.fromJson(json, type);
}
/**
* 校验是否为get方式提交的参数
*
* @param paras
* @return
*/
public static boolean validateModel(String paras) {
return Pattern.compile("\\w*[^&=]*=\\w*[^&=]*&?").matcher(paras).find();
}
/**
* 取出java.sql.ResultSet中的数据,返回一个包含该ResultSet所有数据的ArrayList<JsonObject>对象
* @param rs
* @return 包含所有数据的ArrayList<JsonObject>对象
* @throws SQLException
*/
public static List<JsonObject> resultSetToJsonObjList(ResultSet rs) {
if (rs == null) {
return null;
}
List<JsonObject> list = new ArrayList<JsonObject>();
try {
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍历ResultSet中的每条数据
while (rs.next()) {
// json对象
JsonObject jsonObj = new JsonObject();
// 遍历每一列
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
String value = rs.getString(columnName);
if (StringUtil.isNotBlank(value)) {
jsonObj.addProperty(columnName, value);
}
}
list.add(jsonObj);
}
} catch (SQLException e) {
log.error("GsonUtil.resultSetToJsonObjectList Exception :", e);
}
return list;
}
/**
* 取出java.sql.ResultSet中的数据,并返回一个包含一条数据的JsonObject对象
* @param rs
* @return 包含一条数据的JsonObject对象
* @throws SQLException
* @Attention 确定ResultSet只有一条数据或只取ResultSet第一条数据时使用
*/
public static JsonObject resultSetToJsonObject(ResultSet rs) {
if (rs == null) {
return null;
}
JsonObject jsonObj = null;
try {
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
if (rs.next()) {
jsonObj = new JsonObject();
// 遍历每一列
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
String value = rs.getString(columnName);
/**
* 暂时的策略 空值就不往里放了
*/
if (StringUtil.isNotBlank(value)) {
jsonObj.addProperty(columnName, value);
}
}
}
} catch (SQLException e) {
log.error("GsonUtil.resultSetToJsonObject Exception :", e);
}
return (jsonObj == null || jsonObj.size() == 0) ? null : jsonObj;
}
/**
* java.sql.ResultSet 转JsonObject字符串
* @param rs
* @return json字符串
*/
public static String resultSetToJsonStr(ResultSet rs) {
JsonObject jsonObj = resultSetToJsonObject(rs);
return jsonObj == null ? "" : jsonObj.toString();
}
/**
* java.sql.ResultSet 转json的List型字符串
* @param rs
* @return ResultSet所含数据的json字符串(List形式)
*/
public static String resultSetToJsonListStr(ResultSet rs) {
List<JsonObject> list = resultSetToJsonObjList(rs);
return list.isEmpty() == true ? "" : gson.toJson(list);
}
/**
*
* @param key
* @param JsonObject
* @return
* @Description: 判断JsonObject中是否含有该key
*/
public static boolean containsKey(String key, JsonObject JsonObject) {
return JsonObject.get(key) == null ? false : true;
};
public static void main(String[] args) {
}
}
GsonUtil 工具类 1.3.3
最新推荐文章于 2024-06-28 03:31:56 发布