使用 google gson 转换Timestamp或Date类型为JSON字符串.
来源:互联网 发布:安卓推送联盟 知乎 编辑:程序博客网 时间:2024/05/16 11:51
创建类型适配类:
- import java.lang.reflect.Type;
- import java.sql.Timestamp;
- import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- 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;
- public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{
- private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) {
- String dateFormatAsString = format.format(new Date(src.getTime()));
- return new JsonPrimitive(dateFormatAsString);
- }
- public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
- if (!(json instanceof JsonPrimitive)) {
- throw new JsonParseException("The date should be a string value");
- }
- try {
- Date date = format.parse(json.getAsString());
- return new Timestamp(date.getTime());
- } catch (ParseException e) {
- throw new JsonParseException(e);
- }
- }
- }
类型适配类
应用类型适配器 写道
Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class,new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String jsonString = gson.toJson(resourceInfo,ResourceGeoInfo.class);
String jsonString = gson.toJson(resourceInfo,ResourceGeoInfo.class);
输出结果
{"positionTime":"2010-01-07 10:57:27"}
Date 类型的时间转换第二种方式;
- Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
- String jsonString = gson.toJson(new Date(System.currentTimeMillis()),Date.class);
- System.out.println(jsonString);
输出结果:
"2010-01-07 12:24:34"
- 使用 google gson 转换Timestamp或Date类型为JSON字符串.
- 使用 google gson 转换Timestamp或Date类型为JSON字符串.
- 使用 google gson 转换Timestamp或Date类型为JSON字符串
- Oracle 字符串转换TIMESTAMP类型或Date类型
- Oracle 字符串转换TIMESTAMP类型或Date类型
- date类型,怎么转换为timestamp类型?
- 用gson如何处理json转换Timestamp类型
- 字符串转换为Date类型
- oracle数据库中的timestamp类型,转换为date 类型
- 【GSON】复杂集合类型转换为Json
- C#将unix Timestamp转换为Date类型时间
- C#将unix Timestamp转换为Date类型时间
- java转换string类型timestamp为Date对象
- String,date,timestamp 类型转换
- java date类型转换为json
- google 的 gson json字符串转map 或 list
- gson json字符串转换
- 使用Google的Gson实现对象的json字符串之间的转换
- Gson解析date类型 范例
- IPython Quick Reference Card
- C/C++堆、栈及静态数据区详解 (转载)
- vs2012打包部署winForm和WPF应用
- Android相对布局中控件的常用属性【转】
- 使用 google gson 转换Timestamp或Date类型为JSON字符串.
- sprint mvc 事务处理的困扰终于解决了。
- (翻译)Simple MEF Application for Beginners
- Android 关于wifi管理的代码
- 解决ssh的"Write failed: Broken pipe"问题
- Linux xargs命令
- IBM iNotes脱机功能的一个常用使用场景
- [HGE]-源码分析-4 core里的demo和graphics(a)
- C++类模板实现双链表