• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 Google Inc.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package com.google.caliper.json;
18 
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Maps;
21 import com.google.gson.Gson;
22 import com.google.gson.TypeAdapter;
23 import com.google.gson.TypeAdapterFactory;
24 import com.google.gson.reflect.TypeToken;
25 import com.google.gson.stream.JsonReader;
26 import com.google.gson.stream.JsonWriter;
27 
28 import java.io.IOException;
29 import java.lang.reflect.ParameterizedType;
30 import java.lang.reflect.Type;
31 import java.util.HashMap;
32 import java.util.Map;
33 
34 /**
35  * Serializes and deserializes {@link ImmutableMap} instances using a {@link HashMap} as an
36  * intermediary.
37  */
38 final class ImmutableMapTypeAdapterFactory implements TypeAdapterFactory {
39   @SuppressWarnings("unchecked")
create(Gson gson, TypeToken<T> typeToken)40   @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
41     Type type = typeToken.getType();
42     if (typeToken.getRawType() != ImmutableMap.class
43         || !(type instanceof ParameterizedType)) {
44       return null;
45     }
46 
47     com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken =
48         (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>)
49             com.google.common.reflect.TypeToken.of(typeToken.getType());
50     final TypeAdapter<HashMap<?, ?>> hashMapAdapter =
51         (TypeAdapter<HashMap<?, ?>>) gson.getAdapter(
52             TypeToken.get(betterToken.getSupertype(Map.class).getSubtype(HashMap.class)
53                 .getType()));
54     return new TypeAdapter<T>() {
55       @Override public void write(JsonWriter out, T value) throws IOException {
56         HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value);
57         hashMapAdapter.write(out, hashMap);
58       }
59 
60       @Override public T read(JsonReader in) throws IOException {
61         HashMap<?, ?> hashMap = hashMapAdapter.read(in);
62         return (T) ImmutableMap.copyOf(hashMap);
63       }
64     };
65   }
66 }
67