2 * Copyright (C) 2011 Google Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com
.google
.gson
.internal
.bind
;
19 import com
.google
.gson
.Gson
;
20 import com
.google
.gson
.JsonSyntaxException
;
21 import com
.google
.gson
.TypeAdapter
;
22 import com
.google
.gson
.TypeAdapterFactory
;
23 import com
.google
.gson
.reflect
.TypeToken
;
24 import com
.google
.gson
.stream
.JsonReader
;
25 import com
.google
.gson
.stream
.JsonToken
;
26 import com
.google
.gson
.stream
.JsonWriter
;
27 import java
.io
.IOException
;
28 import java
.text
.DateFormat
;
29 import java
.text
.ParseException
;
30 import java
.text
.SimpleDateFormat
;
33 * Adapter for java.sql.Date. Although this class appears stateless, it is not.
34 * DateFormat captures its time zone and locale when it is created, which gives
35 * this class state. DateFormat isn't thread safe either, so this class has
36 * to synchronize its read and write methods.
38 public final class SqlDateTypeAdapter
extends TypeAdapter
<java
.sql
.Date
> {
39 public static final TypeAdapterFactory FACTORY
= new TypeAdapterFactory() {
40 @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
41 public <T
> TypeAdapter
<T
> create(Gson gson
, TypeToken
<T
> typeToken
) {
42 return typeToken
.getRawType() == java
.sql
.Date
.class
43 ?
(TypeAdapter
<T
>) new SqlDateTypeAdapter() : null;
47 private final DateFormat format
= new SimpleDateFormat("MMM d, yyyy");
50 public synchronized java
.sql
.Date
read(JsonReader in
) throws IOException
{
51 if (in
.peek() == JsonToken
.NULL
) {
56 final long utilDate
= format
.parse(in
.nextString()).getTime();
57 return new java
.sql
.Date(utilDate
);
58 } catch (ParseException e
) {
59 throw new JsonSyntaxException(e
);
64 public synchronized void write(JsonWriter out
, java
.sql
.Date value
) throws IOException
{
65 out
.value(value
== null ?
null : format
.format(value
));