GsonUtil 工具類 1.3.3

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) {

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章