toJson 时间格式化
来源:互联网 发布:工业设计主流软件 编辑:程序博客网 时间:2024/06/12 22:55
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()); } }}
0 0
- toJson 时间格式化
- toJSON时间格式化
- $.toJSON
- 格式化时间
- 格式化时间
- 时间格式化
- 格式化时间
- 时间格式化
- 格式化时间
- 格式化时间
- 格式化时间
- 格式化时间
- 格式化时间
- 时间格式化
- 时间格式化
- 格式化时间
- 时间格式化
- 时间格式化
- $filter 在视图和控制器的使用以及自定义带参数的过滤器
- spring注入的方式实现静态方法中使用非静态变量
- Word转PDF(Java实现)
- 1040. 有几个PAT
- Android中ListView分页加载数据
- toJson 时间格式化
- 致刚起步的自己
- 1041. 考试座位号
- 统计学习笔记(3) 监督学习概论(3)
- iOS在后台运行app
- JNI 实战全面解析,jni实战全面解析
- 1042. 字符统计
- 1043. 输出PATest
- 课程练习一-Problem G