JSON知识总结- Gson(五)Date
来源:互联网 发布:中国人在非洲 知乎 编辑:程序博客网 时间:2024/06/06 17:43
使用Gson做java.util.Date的转换,找到了一种方法:
首先要写Date的转化器
package org.ygy.date;import java.lang.reflect.Type;import java.util.Date;import com.google.gson.JsonDeserializationContext;import com.google.gson.JsonDeserializer;import com.google.gson.JsonElement;import com.google.gson.JsonParseException;public class UtilDateDeserializer implements JsonDeserializer<Date> {@Overridepublic Date deserialize(JsonElement json, Type typeOfT,JsonDeserializationContext context) throws JsonParseException {return new Date(json.getAsJsonPrimitive().getAsLong());}}
package org.ygy.date;import java.lang.reflect.Type;import java.util.Date;import com.google.gson.JsonElement;import com.google.gson.JsonPrimitive;import com.google.gson.JsonSerializationContext;import com.google.gson.JsonSerializer;public class UtilDateSerializer implements JsonSerializer<Date> {@Overridepublic JsonElement serialize(Date src, Type typeOfSrc,JsonSerializationContext context) {return new JsonPrimitive(src.getTime());}}测试:
package org.ygy.date;import java.text.DateFormat;import java.util.Date;import org.junit.Test;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class DateTest {public static String toJson(Date date) {Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtilDateSerializer()).setDateFormat(DateFormat.LONG).create();return gson.toJson(date);}public static Date fromJson(String json) {Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtilDateDeserializer()).setDateFormat(DateFormat.LONG).create();return gson.fromJson(json , Date.class);}@Testpublic void testDate() {String json = toJson(new Date());System.out.println("json->" + json);Date date = fromJson(json);System.out.println(date.getTime());}}结果显示:
- JSON知识总结- Gson(五)Date
- JSON知识总结-Gson(一)
- JSON知识总结- Gson(二)
- JSON知识总结- Gson(三)
- JSON知识总结- Gson(四)List和Map
- Gson 解析JSON 五
- gson解析json(总结)
- GSON解析json数据总结
- Android总结之json解析(FastJson Gson 对比)
- Android总结之json解析(FastJson Gson 对比)
- JSON工具(gson)
- Gson 生成和解析带Date类型的json
- Gson 生成和解析带Date类型的json
- Gson 生成和解析带Date类型的json
- mybastis知识总结(五)事物管理
- oc 知识总结五(NSDate)
- json知识总结
- JSON知识总结
- windows消息和消息队列
- C#解压或压缩文件夹
- 大数据:推荐系统
- linux驱动开发基础
- FFMpeg的使用可以提高视频的加载速度
- JSON知识总结- Gson(五)Date
- struts2_Action之间的重定向传参
- 谈程序员所看重的氛围
- setsockopt() ioctlsocket() sol_socket 详解
- Operating Systems : Design and implementation 读书笔记
- 通过命令行开启和结束应用程序
- FileChannel 使用
- debian关机时的beep声响
- vector 释放内存 swap