toJson 时间格式化
2016-03-30 17:39
477 查看
import java.lang.reflect.Type; import java.text.DateFormat; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; /** * Json转换工具 * * @Filename: JsonUtil.java * @Version: 1.0 * */ public final class JsonUtil { private static org.apache.log4j.Logger log = org.apache.log4j.LogManager .getLogger(JsonUtil.class); /** * 将JSON字符串反序列化为Java对象。 * @param json JSON字符串 * @return * <li>json字符串为空时返回null; * <li>json字符串为无效JSON格式时,会记录日志,返回null; */ public static final <T> T fromJson(String json) { if (StringUtil.isEmpty(json)) return null; try { Type type = new TypeToken<T>() { }.getType(); Gson gson = new Gson(); return gson.fromJson(json, type); } catch (Exception e) { log.warn("Invalidate json format:" + json, e); return null; } } /** * 将Java对象序列化成JSON字符串。 * @param obj * @return */ public static final String toJson(Object obj) { if (obj == null) return null; try { GsonBuilder gb = new GsonBuilder(); gb.setDateFormat("yyyy-MM-dd HH:mm:ss"); return gb.create().toJson(obj); } catch (Exception e) { log.warn("Can not serialize object to json", e); return null; } } /** * 格式时间成毫秒值 * @param obj * @return */ public static final String toFormatJson(Object obj) { if (obj == null) return null; try { GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG); gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG); return gb.create().toJson(obj); } catch (Exception e) { log.warn("Can not serialize object to json", e); return null; } } public static class DateDeserializer implements JsonDeserializer<java.util.Date> { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new java.util.Date(json.getAsJsonPrimitive().getAsLong()); } } public static class DateSerializer implements JsonSerializer<Date> { public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getTime()); } } }
相关文章推荐
- 关于js的几个特点
- bzoj 1449 [JSOI2009]球队收益(费用拆分,最小费用流)
- bzoj 1560 [JSOI2009]火星藏宝图(DP)
- jspatch 的简单原理理解
- bzoj1823 [JSOI2010]满汉全席(2-SAT)
- bzoj2208 [Jsoi2010]连通数(scc+bitset)
- BZOJ1015 [JSOI2008]星球大战starwar(并查集)
- Ajax、servlet、jsp、JSON数据交互以及跳转问题
- JSP跳转页面的几种方式
- 关于js页面时间判断,和一些杂项
- 对象转JSON注意点
- js的工作原理
- js初学笔记(二)
- javascript笔记——JavaScript经典实例
- 谈一谈js中的执行环境及作用域
- 序列化和反序列化(二)——让我们聊聊Json这个家伙吧!
- json工具类
- Angular JS中变量定义的基本原则
- js中的执行环境及作用域
- 汇总前端最最常用的JS代码片段