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:org.codice.admin.router.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }/*w ww.j  a va  2 s.com*/

    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().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:org.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java

License:Open Source License

private <E> TypeAdapter<Multiset<E>> newMultisetAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<Multiset<E>>() {
        public void write(JsonWriter out, Multiset<E> multiset) throws IOException {
            if (multiset == null) {
                out.nullValue();/* w w w  .  j  a va 2 s .  c o  m*/
                return;
            }

            out.beginArray();
            for (Entry<E> entry : multiset.entrySet()) {
                out.beginObject();
                out.name("id");
                elementAdapter.write(out, entry.getElement());
                out.name("count");
                out.value(entry.getCount());
                out.endObject();
            }
            out.endArray();
        }

        public Multiset<E> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }

            Multiset<E> result = LinkedHashMultiset.create();
            in.beginArray();
            while (in.hasNext()) {
                in.beginObject();
                in.nextName(); // "id"
                E element = elementAdapter.read(in);
                in.nextName(); // "count"
                int count = in.nextInt();
                result.add(element, count);
                in.endObject();
            }
            in.endArray();
            return result;
        }
    };
}

From source file:org.immutables.mongo.bson4gson.GsonCodecs.java

License:Apache License

/**
 * Build a TypeAdapter from {@link Codec} opposite of {@link #codecFromTypeAdapter(Class, TypeAdapter)}.
 *
 * @param codec existing codec/*from w  w w .j  a  va2s .co  m*/
 * @return type adapter which delegates calls to a codec.
 */
public static <T> TypeAdapter<T> typeAdapterFromCodec(final Codec<T> codec) {
    Preconditions.checkNotNull(codec, "codec");
    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            BsonWriter writer = (BsonWriter) out;
            org.bson.BsonWriter delegate = writer.unwrap();
            codec.encode(delegate, value, EncoderContext.builder().build());
        }

        @Override
        public T read(JsonReader in) throws IOException {
            BsonReader reader = (BsonReader) in;
            org.bson.BsonReader delegate = reader.unwrap();
            return codec.decode(delegate, DecoderContext.builder().build());
        }
    };
}

From source file:org.jclouds.json.internal.IgnoreNullFluentIterableTypeAdapterFactory.java

License:Apache License

protected <E> TypeAdapter<FluentIterable<E>> newFluentIterableAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<FluentIterable<E>>() {
        public void write(JsonWriter out, FluentIterable<E> value) throws IOException {
            out.beginArray();/*from w  ww . ja  va 2 s  .  co m*/
            for (E element : value) {
                elementAdapter.write(out, element);
            }
            out.endArray();
        }

        public FluentIterable<E> read(JsonReader in) throws IOException {
            in.beginArray();
            Builder<E> builder = ImmutableList.<E>builder();
            while (in.hasNext()) {
                E element = elementAdapter.read(in);
                if (element != null)
                    builder.add(element);
            }
            in.endArray();
            return FluentIterable.from(builder.build());
        }
    }.nullSafe();
}

From source file:org.jclouds.json.internal.IgnoreNullIterableTypeAdapterFactory.java

License:Apache License

protected <E> TypeAdapter<Iterable<E>> newIterableAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<Iterable<E>>() {
        public void write(JsonWriter out, Iterable<E> value) throws IOException {
            out.beginArray();//from   ww  w . j  a v  a2s.c  o m
            for (E element : value) {
                elementAdapter.write(out, element);
            }
            out.endArray();
        }

        public Iterable<E> read(JsonReader in) throws IOException {
            in.beginArray();
            Builder<E> builder = ImmutableList.<E>builder();
            while (in.hasNext()) {
                E element = elementAdapter.read(in);
                if (element != null)
                    builder.add(element);
            }
            in.endArray();
            return builder.build();
        }
    }.nullSafe();
}

From source file:org.jclouds.json.internal.IgnoreNullMapTypeAdapterFactory.java

License:Apache License

private <K, V> TypeAdapter<Map<K, V>> newMapAdapter(final TypeAdapter<K> keyAdapter,
        final TypeAdapter<V> valueAdapter) {
    return new TypeAdapter<Map<K, V>>() {
        public void write(JsonWriter out, Map<K, V> value) throws IOException {
            out.beginObject();/*  w  w w. j a v  a2  s. co m*/
            for (Map.Entry<K, V> element : value.entrySet()) {
                out.name(String.valueOf(element.getKey()));
                valueAdapter.write(out, element.getValue());
            }
            out.endObject();
        }

        public Map<K, V> read(JsonReader in) throws IOException {
            Map<K, V> result = Maps.newLinkedHashMap();
            in.beginObject();
            while (in.hasNext()) {
                JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
                K name = keyAdapter.read(in);
                V value = valueAdapter.read(in);
                if (value != null)
                    result.put(name, value);
            }
            in.endObject();
            return result;
        }
    }.nullSafe();
}

From source file:org.jclouds.json.internal.IgnoreNullMultimapTypeAdapterFactory.java

License:Apache License

private <K, V> TypeAdapter<Multimap<K, V>> newMapAdapter(final TypeAdapter<K> keyAdapter,
        final TypeAdapter<V> valueAdapter) {
    return new TypeAdapter<Multimap<K, V>>() {
        public void write(JsonWriter out, Multimap<K, V> map) throws IOException {
            out.beginObject();/*w w w  .j  a v a  2  s . co  m*/
            for (K key : map.keySet()) {
                out.name(String.valueOf(key));
                out.beginArray();
                for (V value : map.get(key)) {
                    valueAdapter.write(out, value);
                }
                out.endArray();
            }
            out.endObject();
        }

        public Multimap<K, V> read(JsonReader in) throws IOException {
            ImmutableMultimap.Builder<K, V> result = ImmutableListMultimap.builder();
            in.beginObject();
            while (in.hasNext()) {
                JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
                K name = keyAdapter.read(in);
                in.beginArray();
                while (in.hasNext()) {
                    V value = valueAdapter.read(in);
                    if (value != null)
                        result.put(name, value);
                }
                in.endArray();
            }
            in.endObject();
            return result.build();
        }
    }.nullSafe();
}

From source file:org.jclouds.json.internal.IgnoreNullSetTypeAdapterFactory.java

License:Apache License

private <E> TypeAdapter<Set<E>> newSetAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<Set<E>>() {
        public void write(JsonWriter out, Set<E> value) throws IOException {
            out.beginArray();//from  w ww.  ja va2 s. c  om
            for (E element : value) {
                elementAdapter.write(out, element);
            }
            out.endArray();
        }

        public Set<E> read(JsonReader in) throws IOException {
            Set<E> result = Sets.newLinkedHashSet();
            in.beginArray();
            while (in.hasNext()) {
                E element = elementAdapter.read(in);
                if (element != null)
                    result.add(element);
            }
            in.endArray();
            return result;
        }
    }.nullSafe();
}

From source file:org.jclouds.json.internal.OptionalTypeAdapterFactory.java

License:Apache License

protected <E> TypeAdapter<Optional<E>> newOptionalAdapter(final TypeAdapter<E> elementAdapter) {
    return new TypeAdapter<Optional<E>>() {
        public void write(JsonWriter out, Optional<E> value) throws IOException {
            if (!value.isPresent()) {
                out.nullValue();/*from w  w w  . ja v  a2s. co m*/
                return;
            }
            elementAdapter.write(out, value.get());
        }

        public Optional<E> read(JsonReader in) throws IOException {
            Optional<E> result = Optional.absent();
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
            } else {
                E element = elementAdapter.read(in);
                if (element != null) {
                    result = Optional.of(element);
                }
            }
            return result;
        }
    };
}

From source file:org.lanternpowered.server.script.json.CatalogTypeTypeAdapterFactory.java

License:MIT License

@Nullable
@Override//from  w  w w  . ja v a2s  .c  o  m
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<? super T> raw = type.getRawType();
    if (!CatalogType.class.isAssignableFrom(raw)) {
        return null;
    }
    final TypeAdapter<JsonElement> jsonElementTypeAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            jsonElementTypeAdapter.write(out, new JsonPrimitive(((CatalogType) value).getId()));
        }

        @Override
        public T read(JsonReader in) throws IOException {
            final String id = jsonElementTypeAdapter.read(in).getAsString();
            //noinspection unchecked
            return (T) Sponge.getRegistry().getType((Class<? extends CatalogType>) raw, id)
                    .orElseThrow(() -> new IllegalArgumentException(
                            "There does not exist a " + raw.getName() + " with id: " + id));
        }
    };
}