1
16
17 package com.google.gson.internal.bind;
18
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.sql.Time;
29 import java.text.DateFormat;
30 import java.text.ParseException;
31 import java.text.SimpleDateFormat;
32 import java.util.Date;
33
34
40 public final class TimeTypeAdapter extends TypeAdapter<Time> {
41 public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
42 @SuppressWarnings("unchecked")
43 @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
44 return typeToken.getRawType() == Time.class ? (TypeAdapter<T>) new TimeTypeAdapter() : null;
45 }
46 };
47
48 private final DateFormat format = new SimpleDateFormat("hh:mm:ss a");
49
50 @Override public synchronized Time read(JsonReader in) throws IOException {
51 if (in.peek() == JsonToken.NULL) {
52 in.nextNull();
53 return null;
54 }
55 try {
56 Date date = format.parse(in.nextString());
57 return new Time(date.getTime());
58 } catch (ParseException e) {
59 throw new JsonSyntaxException(e);
60 }
61 }
62
63 @Override public synchronized void write(JsonWriter out, Time value) throws IOException {
64 out.value(value == null ? null : format.format(value));
65 }
66 }
67