對象POJO和JSON互轉
public class JsonUtil { /** * JSON 轉 POJO */ public static <T> T getObject(String pojo, Class<T> tclass) { try { return JSONObject.parseObject(pojo, tclass); } catch (Exception e) { log.error(tclass + "轉 JSON 失敗"); } return null; } /** * POJO 轉 JSON */ public static <T> String getJson(T tResponse){ String pojo = JSONObject.toJSONString(tResponse); return pojo; } }
List集合和JSON互轉工具類
public class JsonListUtil { /** * List<T> 轉 json 保存到數據庫 */ public static <T> String listToJson(List<T> ts) { String jsons = JSON.toJSONString(ts); return jsons; } /** * json 轉 List<T> */ public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) { @SuppressWarnings("unchecked") List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz); return ts; } }