I can't seem to get gson to convert a Date to UTC time in java.... Here is my code...

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
//This is the format I want, which according to the ISO8601 standard - Z specifies UTC - 'Zulu' time

Date now=new Date();          
System.out.println(now);       
System.out.println(now.getTimezoneOffset());
System.out.println(gson.toJson(now));

Here is my Output

Thu Sep 25 18:21:42 BST 2014           // Time now - in British Summer Time 
-60                                    // As expected : offset is 1hour from UTC    
"2014-09-25T18:21:42.026Z"             // Uhhhh this is not UTC ??? Its still BST !!

The gson result I want and what I was expecting

"2014-09-25T17:21:42.026Z"

I can clearly just subtract 1hr before the call toJson but this seems to be a hack. How can I configure gson to always convert to UTC ?

推荐答案

After some further research, it appears this is a known issue. The gson default serializer always defaults to your local timezone, and doesn't allow you to specify the timezone. See the following link.....

https://code.google.com/p/google-gson/issues/detail?id=281

The solution is to create a custom gson type adaptor as demonstrated in the link:

// this class can't be static
public class GsonUTCDateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {

    private final DateFormat dateFormat;

    public GsonUTCDateAdapter() {
      dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);      //This is the format I need
      dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                               //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
    }

    @Override public synchronized JsonElement serialize(Date date,Type type,JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(dateFormat.format(date));
    }

    @Override public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
      try {
        return dateFormat.parse(jsonElement.getAsString());
      } catch (ParseException e) {
        throw new JsonParseException(e);
      }
    }
}

然后注册如下:

  Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
  Date now=new Date();
  System.out.println(gson.toJson(now));

现在可以正确地输出UTC格式的日期

"2014-09-25T17:21:42.026Z"

感谢链接作者.

Json相关问答推荐

Jolt转换,如果任何字段为空,则将对象值设置为空

在T—SQL中将STR_AGG与JSON_ARRAY结合起来

Vega-Lite:文本笔画在外部

当有嵌套数组而没有嵌套数组时,展平JSON

从先前的REST调用创建动态JSON主体

与错误相关的未定义&Quot;不是有效的JSON

有没有办法让serde_json正确/不正确地处理NaN、inf和-inf(IEEE 754特殊标准)?

如何将属性拆分为嵌套的JSON内容?

将带有::text[]的JSON数组转换未按预期工作

Jolt 转换数组对象并将某些字段移动到嵌套数组

Jolt 规范将父对象中的所有键应用于数组中的所有对象

将 colly 包输出文本添加到 golang 中的映射

MarkLogic REST 资源 API - 仅使用一个 POST 请求修补多个文档

提交后使用 Rails 7 结合 JSON 标签进行标记

TSQL FOR JSON 嵌套值

解析 JSON API 响应

Angular 2/Web Api - json 解析错误语法错误意外结束输入

将 PHP 结果数组转换为 JSON

我可以使用空字符串作为对象标识符吗?

如何使用 Gson 解码具有未知字段的 JSON?