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 17package com.google.caliper.json; 18 19import com.google.common.collect.ImmutableMap; 20import com.google.common.collect.Maps; 21import com.google.gson.Gson; 22import com.google.gson.TypeAdapter; 23import com.google.gson.TypeAdapterFactory; 24import com.google.gson.reflect.TypeToken; 25import com.google.gson.stream.JsonReader; 26import com.google.gson.stream.JsonWriter; 27 28import java.io.IOException; 29import java.lang.reflect.ParameterizedType; 30import java.lang.reflect.Type; 31import java.util.HashMap; 32import java.util.Map; 33 34/** 35 * Serializes and deserializes {@link ImmutableMap} instances using a {@link HashMap} as an 36 * intermediary. 37 */ 38final class ImmutableMapTypeAdapterFactory implements TypeAdapterFactory { 39 @SuppressWarnings("unchecked") 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