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
;
29 import java
.text
.DateFormat
;
30 import java
.text
.ParseException
;
31 import java
.text
.SimpleDateFormat
;
32 import java
.util
.Date
;
35 * Adapter for Time. Although this class appears stateless, it is not.
36 * DateFormat captures its time zone and locale when it is created, which gives
37 * this class state. DateFormat isn't thread safe either, so this class has
38 * to synchronize its read and write methods.
40 public final class TimeTypeAdapter
extends TypeAdapter
<Time
> {
41 public static final TypeAdapterFactory FACTORY
= new TypeAdapterFactory() {
42 @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
43 public <T
> TypeAdapter
<T
> create(Gson gson
, TypeToken
<T
> typeToken
) {
44 return typeToken
.getRawType() == Time
.class ?
(TypeAdapter
<T
>) new TimeTypeAdapter() : null;
48 private final DateFormat format
= new SimpleDateFormat("hh:mm:ss a");
50 @Override public synchronized Time
read(JsonReader in
) throws IOException
{
51 if (in
.peek() == JsonToken
.NULL
) {
56 Date date
= format
.parse(in
.nextString());
57 return new Time(date
.getTime());
58 } catch (ParseException e
) {
59 throw new JsonSyntaxException(e
);
63 @Override public synchronized void write(JsonWriter out
, Time value
) throws IOException
{
64 out
.value(value
== null ?
null : format
.format(value
));