gsonを使用してJavaの日付をUTCに変換する 質問する

gsonを使用してJavaの日付をUTCに変換する 質問する

gson で Java の日付を UTC 時間に変換できないようです... これが私のコードです...

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

これが私の出力です

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 !!

私が望んでいたgsonの結果と期待していたもの

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

明らかに、Json を呼び出す前に 1 時間減算するだけで済みますが、これはハックのようです。常に UTC に変換するように gson を構成するにはどうすればよいでしょうか?

ベストアンサー1

さらに調査してみると、これは既知の問題であることがわかりました。gson のデフォルト シリアライザーは常にローカル タイムゾーンをデフォルトに設定し、タイムゾーンを指定することはできません。次のリンクを参照してください.....

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

解決策は、リンクに示されているように、カスタム gson 型アダプターを作成することです。

// 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"

リンクの作成者に感謝します。

おすすめ記事