• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
使用 google gson 转换Timestamp为JSON字符串
package com.test.base;

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");

    @Override
    public Timestamp deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        if (!(jsonElement instanceof JsonPrimitive)) {
            throw new JsonParseException("The data should be a string value");
        }
        try {
            Date date = format.parse(jsonElement.getAsString());
            return new Timestamp(date.getTime());
        } catch (ParseException e) {
            throw new JsonParseException(e);
        }
    }

    @Override
    public JsonElement serialize(Timestamp timestamp, Type type, JsonSerializationContext jsonSerializationContext) {
        String dataFormatAsString = format.format(new Date(timestamp.getTime()));
        return new JsonPrimitive(dataFormatAsString);
    }

}
    @Test
    public void gsonTest() {
        Gson gson1 = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        CascadeReport tem = new CascadeReport();
        tem.setDate(new Timestamp(new Date().getTime()));
        tem.setDepartment("武汉刑侦");
        String jsonString = gson1.toJson(tem, CascadeReport.class);
        System.out.println(jsonString);
        //////////////////////////////////////////////////////////
        String reportData = "[{date:\"2016-01-01 09:00:01\",department:\"xxxx\",ipAddress:\"192.168.120.120\",failedNum:2,ruleIDs:\"1002,1003\",regionCode:168430083,account:\"李四\",type:1 }]";
        List<CascadeReport> list = gson.fromJson(reportData, new TypeToken<List<CascadeReport>>() {
        }.getType());
        System.out.println(list.get(0).getDate().toGMTString());
    }

 

posted on 2016-04-29 10:07  山高我为峰  阅读(2125)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3