Example usage for com.google.gson TypeAdapter TypeAdapter

List of usage examples for com.google.gson TypeAdapter TypeAdapter

Introduction

In this page you can find the example usage for com.google.gson TypeAdapter TypeAdapter.

Prototype

TypeAdapter

Source Link

Usage

From source file:com.github.sheigutn.pushbullet.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from  w  w w. j  a v  a2  s.c  o  m

    if (baseDelegateAdapter == null) {
        baseDelegateAdapter = gson.getDelegateAdapter(RuntimeTypeAdapterFactory.this, TypeToken.get(baseType));
    }

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @SuppressWarnings("unchecked")
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); //remove(typeFieldName) changed to get(typeFieldName)
            if (labelJsonElement == null) {
                return (R) baseDelegateAdapter.fromJsonTree(jsonElement);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            //if (jsonObject.has(typeFieldName)) {
            //    throw new JsonParseException("cannot serialize " + srcType.getName()
            //            + " because it already defines a field named " + typeFieldName); <-- Commented
            //}
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:com.google.caliper.json.ImmutableListTypeAdatperFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w w w.  ja v  a 2  s.c  o  m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != ImmutableList.class || !(type instanceof ParameterizedType)) {
        return null;
    }

    com.google.common.reflect.TypeToken<ImmutableList<?>> betterToken = (com.google.common.reflect.TypeToken<ImmutableList<?>>) com.google.common.reflect.TypeToken
            .of(typeToken.getType());
    final TypeAdapter<ArrayList<?>> arrayListAdapter = (TypeAdapter<ArrayList<?>>) gson.getAdapter(
            TypeToken.get(betterToken.getSupertype(List.class).getSubtype(ArrayList.class).getType()));
    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            ArrayList<?> arrayList = Lists.newArrayList((List<?>) value);
            arrayListAdapter.write(out, arrayList);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            ArrayList<?> arrayList = arrayListAdapter.read(in);
            return (T) ImmutableList.copyOf(arrayList);
        }
    };
}

From source file:com.google.caliper.json.ImmutableMapTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from   w ww  . j ava2 s  .com
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != ImmutableMap.class || !(type instanceof ParameterizedType)) {
        return null;
    }

    com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken = (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>) com.google.common.reflect.TypeToken
            .of(typeToken.getType());
    final TypeAdapter<HashMap<?, ?>> hashMapAdapter = (TypeAdapter<HashMap<?, ?>>) gson
            .getAdapter(TypeToken.get(betterToken.getSupertype(Map.class).getSubtype(HashMap.class).getType()));
    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value);
            hashMapAdapter.write(out, hashMap);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            HashMap<?, ?> hashMap = hashMapAdapter.read(in);
            return (T) ImmutableMap.copyOf(hashMap);
        }
    };
}

From source file:com.google.caliper.json.ImmutableMultimapTypeAdapterFactory.java

License:Apache License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter<T> create(Gson gson, com.google.gson.reflect.TypeToken<T> typeToken) {
    if (ImmutableListMultimap.class.isAssignableFrom(typeToken.getRawType())) {
        TypeToken<Map<?, List<?>>> mapToken = getMapOfListsToken((TypeToken) TypeToken.of(typeToken.getType()));
        final TypeAdapter<Map<?, List<?>>> adapter = (TypeAdapter<Map<?, List<?>>>) gson
                .getAdapter(com.google.gson.reflect.TypeToken.get(mapToken.getType()));
        return new TypeAdapter<T>() {
            @Override/* w  ww . j  a va 2  s.c  o  m*/
            public void write(JsonWriter out, T value) throws IOException {
                ImmutableListMultimap<?, ?> multimap = (ImmutableListMultimap<?, ?>) value;
                adapter.write(out, (Map) multimap.asMap());
            }

            @Override
            public T read(JsonReader in) throws IOException {
                Map<?, List<?>> value = adapter.read(in);
                ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder();
                for (Entry<?, List<?>> entry : value.entrySet()) {
                    builder.putAll(entry.getKey(), entry.getValue());
                }
                return (T) builder.build();
            }
        };
    } else if (ImmutableSetMultimap.class.isAssignableFrom(typeToken.getRawType())) {
        TypeToken<Map<?, Set<?>>> mapToken = getMapOfSetsToken((TypeToken) TypeToken.of(typeToken.getType()));
        final TypeAdapter<Map<?, Set<?>>> adapter = (TypeAdapter<Map<?, Set<?>>>) gson
                .getAdapter(com.google.gson.reflect.TypeToken.get(mapToken.getType()));
        return new TypeAdapter<T>() {
            @Override
            public void write(JsonWriter out, T value) throws IOException {
                ImmutableSetMultimap<?, ?> multimap = (ImmutableSetMultimap<?, ?>) value;
                adapter.write(out, (Map) multimap.asMap());
            }

            @Override
            public T read(JsonReader in) throws IOException {
                Map<?, Set<?>> value = adapter.read(in);
                ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder();
                for (Entry<?, Set<?>> entry : value.entrySet()) {
                    builder.putAll(entry.getKey(), entry.getValue());
                }
                return (T) builder.build();
            }
        };
    } else {
        return null;
    }
}

From source file:com.google.caliper.json.NaturallySortedMapTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w ww .j  a va  2  s . c  o  m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (!CLASSES.contains(typeToken.getRawType()) || !(type instanceof ParameterizedType)) {
        return null;
    }

    com.google.common.reflect.TypeToken<SortedMap<?, ?>> betterToken = (com.google.common.reflect.TypeToken<SortedMap<?, ?>>) com.google.common.reflect.TypeToken
            .of(typeToken.getType());
    final TypeAdapter<Map<?, ?>> mapAdapter = (TypeAdapter<Map<?, ?>>) gson
            .getAdapter(TypeToken.get(betterToken.getSupertype(Map.class).getType()));
    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            TreeMap<?, ?> treeMap = Maps.newTreeMap((SortedMap<?, ?>) value);
            mapAdapter.write(out, treeMap);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public T read(JsonReader in) throws IOException {
            TreeMap treeMap = Maps.newTreeMap();
            treeMap.putAll(mapAdapter.read(in));
            return (T) treeMap;
        }
    };
}

From source file:com.gsaul.AethonSimulator.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from   ww w. j  a  v  a 2s  .co  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); //used to be .remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:com.hkm.disqus.api.gson.BlacklistsEntryTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    // Return null if not a blacklist entry object
    if (!type.getType().equals(Entry.class)) {
        return null;
    }/*from  ww  w.  ja va  2s  .  c  o m*/

    // Get delegate
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // Return adapter
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
            JsonElement value = jsonTree.getAsJsonObject().get("value");

            // Process the entry with the delegate
            T entry = delegate.fromJsonTree(jsonTree);

            // Process value if needed
            if (value.isJsonObject()) {
                ((Entry) entry).value = gson.fromJson(value, User.class);
            }

            // Return entry
            return entry;
        }

    };
}

From source file:com.hkm.disqus.api.gson.PostTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    // Return null if not a post object
    if (!type.getType().equals(Post.class)) {
        return null;
    }/*from www  .  ja v a2  s.c  om*/

    // Get delegate
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // Return adapter
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
            JsonElement forum = jsonTree.getAsJsonObject().get("forum");
            JsonElement thread = jsonTree.getAsJsonObject().get("thread");

            // Process the post with the delegate
            T post = delegate.fromJsonTree(jsonTree);

            // Process forum and thread if needed
            if (forum.isJsonObject()) {
                ((Post) post).forum = gson.fromJson(forum, Forum.class);
            }
            if (thread.isJsonObject()) {
                ((Post) post).thread = gson.fromJson(thread, Thread.class);
            }

            // Return post
            return post;
        }

    };

}

From source file:com.hkm.disqus.api.gson.ThreadTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    // Return null if not the thread type
    if (!type.getType().equals(Thread.class)) {
        return null;
    }//from   w  w w .ja  v  a2  s.  com

    // Get delegate
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // Return adapter
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
            JsonElement forum = jsonTree.getAsJsonObject().get("forum");
            JsonElement author = jsonTree.getAsJsonObject().get("author");
            JsonElement category = jsonTree.getAsJsonObject().get("category");

            // Process the thread with the delegate
            T thread = delegate.fromJsonTree(jsonTree);

            // Process forum and author if needed
            if (forum.isJsonObject()) {
                ((Thread) thread).forum = gson.fromJson(forum, Forum.class);
            }
            if (author.isJsonObject()) {
                ((Thread) thread).author = gson.fromJson(author, User.class);
            }
            if (category.isJsonObject()) {
                ((Thread) thread).category = gson.fromJson(category, Category.class);
            }

            // Return thread
            return thread;
        }

    };

}

From source file:com.ibm.og.client.ApacheClient.java

License:Open Source License

private Gson createGson() {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setLongSerializationPolicy(LongSerializationPolicy.STRING)
            .registerTypeAdapter(Double.class, new TypeAdapter<Double>() {
                @Override/*w ww  .j av a 2  s  .  c o m*/
                public void write(final JsonWriter out, final Double value) throws IOException {
                    // round decimals to 2 places
                    out.value(new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue());
                }

                @Override
                public Double read(final JsonReader in) throws IOException {
                    return in.nextDouble();
                }
            }.nullSafe()).create();
}