zoukankan      html  css  js  c++  java
  • 使用 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());
        }
  • 相关阅读:
    面向对象一: 数据加载器完成缓存
    软件开发模式总结
    失业求职随便接个单
    恭喜蓝网5巨头输了
    mysql安装及改端口
    解决NAVICAT 无法连接MYSQL8.0.12_可视化工具无法连接 MYSQL 8.0
    c#截取两个指定字符串中间的字符串
    匹配2关键字得结果
    怎么才能更好伪原创
    AntiCrawlerSolution(反爬解决方案)
  • 原文地址:https://www.cnblogs.com/liaojie970/p/5445301.html
Copyright © 2011-2022 走看看