• 使用 google gson 转换Timestamp或Date类型为JSON字符串.


    1. import java.lang.reflect.Type;  
    2. import java.sql.Timestamp;  
    3. import java.text.DateFormat;  
    4. import java.text.ParseException;  
    5. import java.text.SimpleDateFormat;  
    6. import java.util.Date;  
    7.   
    8. import com.google.gson.JsonDeserializationContext;  
    9. import com.google.gson.JsonDeserializer;  
    10. import com.google.gson.JsonElement;  
    11. import com.google.gson.JsonParseException;  
    12. import com.google.gson.JsonPrimitive;  
    13. import com.google.gson.JsonSerializationContext;  
    14. import com.google.gson.JsonSerializer;  
    15.   
    16. public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{  
    17.     private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    18.     public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) {  
    19.         String dateFormatAsString = format.format(new Date(src.getTime()));  
    20.         return new JsonPrimitive(dateFormatAsString);  
    21.     }  
    22.   
    23.     public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {  
    24.         if (!(json instanceof JsonPrimitive)) {  
    25.             throw new JsonParseException("The date should be a string value");  
    26.         }  
    27.   
    28.         try {  
    29.             Date date = format.parse(json.getAsString());  
    30.             return new Timestamp(date.getTime());  
    31.         } catch (ParseException e) {  
    32.             throw new JsonParseException(e);  
    33.         }  
    34.     }  
    35.   

      类型适配类

       应用类型适配器 写道

    Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class,new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    String jsonString = gson.toJson(resourceInfo,ResourceGeoInfo.class);

     输出结果

    {"positionTime":"2010-01-07 10:57:27"}
     
     

    Date 类型的时间转换第二种方式;

    Java代码  收藏代码
    1. Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();  
    2. String jsonString = gson.toJson(new Date(System.currentTimeMillis()),Date.class);  
    3. System.out.println(jsonString);  

    输出结果:

    "2010-01-07 12:24:34"
  • 相关阅读:
    MapReduce 运行流程概要
    HDFS 读写流程概要
    Hadoop源码分析22:dfsclient概要
    Hadoop源码分析22:dfsclient概要
    Matlab安装SVM/RF工具箱的办法
    最大似然估计、最大后验概率估计、贝叶斯公式的理解
    车牌识别
    BP神经网络
    SVM中核函数的理解
    数据库面试
  • 原文地址:https://www.cnblogs.com/thiaoqueen/p/7285317.html
Copyright © 2020-2023  润新知