Example usage for com.google.gson TypeAdapter write

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

Introduction

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

Prototype

public abstract void write(JsonWriter out, T value) throws IOException;

Source Link

Document

Writes one JSON value (an array, object, string, number, boolean or null) for value .

Usage

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   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 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.json.type.ChoiceConfigTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!ChoiceConfig.class.equals(rawType)) {
        return null;
    }//ww  w. j a v  a  2  s. c o  m

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

    return new TypeAdapter<T>() {
        @Override
        public void write(final JsonWriter out, final T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        @SuppressWarnings("rawtypes")
        public T read(final JsonReader in) throws IOException {
            final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType())
                    .getActualTypeArguments()[0];
            final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class);

            // the tree api is used here rather than the stream api so that the full object can be
            // inspected and we can differentiate between a ChoiceConfig<T> object or the underlying T
            // object itself. With the stream api there would be no way to rewind the stream once this
            // determination is made
            //
            // this logic allows the user to configure a choice of T in both the standard form, or
            // compactly if the default choice weight is sufficient e.g.
            //
            // standard form
            // {"choice": {fields for T object}, "weight": 1.0} <- weight is optional here
            //
            // compact form where default weight is acceptable
            // {fields for T object}
            final JsonElement element = jsonElementAdapter.read(in);
            if (element.isJsonObject()) {
                final JsonObject object = element.getAsJsonObject();
                if (object.entrySet().size() <= 2 && object.has("choice")) {
                    return delegate.fromJsonTree(element);
                }
            }

            return (T) new ChoiceConfig(gson.getAdapter(TypeToken.get(genericType)).fromJsonTree(element));
        }
    }.nullSafe();
}

From source file:com.ibm.og.json.type.ContainerConfigTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!ContainerConfig.class.equals(rawType)) {
        return null;
    }/*ww w . j  a v a2s .  c  om*/

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

    return new TypeAdapter<T>() {
        @Override
        public void write(final JsonWriter out, final T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(final JsonReader in) throws IOException {
            if (JsonToken.STRING == in.peek()) {
                return (T) new ContainerConfig(in.nextString());
            }

            return delegate.read(in);
        }

    }.nullSafe();
}

From source file:com.ibm.og.json.type.FilesizeConfigTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!FilesizeConfig.class.equals(rawType)) {
        return null;
    }//  ww w  .ja v  a 2  s  .  com

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

    return new TypeAdapter<T>() {
        @Override
        public void write(final JsonWriter out, final T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(final JsonReader in) throws IOException {
            if (JsonToken.NUMBER == in.peek()) {
                return (T) new FilesizeConfig(in.nextDouble());
            }

            return delegate.read(in);
        }

    }.nullSafe();
}

From source file:com.ibm.og.json.type.OperationConfigTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!OperationConfig.class.equals(rawType)) {
        return null;
    }//ww  w.java 2s.co m

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

    return new TypeAdapter<T>() {
        @Override
        public void write(final JsonWriter out, final T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(final JsonReader in) throws IOException {
            if (JsonToken.NUMBER == in.peek()) {
                return (T) new OperationConfig(in.nextDouble());
            }

            return delegate.read(in);
        }
    }.nullSafe();
}

From source file:com.ibm.og.json.type.SelectionConfigTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!SelectionConfig.class.equals(rawType)) {
        return null;
    }/*from   w  w w . j a  va  2s . com*/

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

    return new TypeAdapter<T>() {
        @Override
        public void write(final JsonWriter out, final T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(final JsonReader in) throws IOException {
            final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType())
                    .getActualTypeArguments()[0];
            final JsonElement element = gson.getAdapter(JsonElement.class).read(in);

            if (element.isJsonObject()) {
                final JsonObject object = element.getAsJsonObject();
                if (object.entrySet().size() <= 2 && object.has("choices")) {
                    return delegate.fromJsonTree(object);
                } else {
                    return (T) choice(genericType, object);
                }
            } else if (element.isJsonArray()) {
                return (T) choiceList(genericType, element.getAsJsonArray());
            }

            return (T) choice(genericType, element);
        }

        private <S> SelectionConfig<S> choice(final Class<S> clazz, final JsonElement element)
                throws IOException {
            final SelectionConfig<S> config = new SelectionConfig<S>();
            config.choices.add(gson.getAdapter(choiceToken(clazz)).fromJsonTree(element));
            return config;
        }

        private <S> SelectionConfig<S> choiceList(final Class<S> clazz, final JsonArray array)
                throws IOException {
            final SelectionConfig<S> config = new SelectionConfig<S>();
            config.choices = gson.getAdapter(choiceListToken(clazz)).fromJsonTree(array);
            return config;
        }

        // must use guava's TypeToken implementation to create a TypeToken instance with a dynamic
        // type; then convert back to gson's TypeToken implementation for use in calling code. See:
        // https://groups.google.com/forum/#!topic/guava-discuss/HdBuiO44uaw
        private <S> TypeToken<ChoiceConfig<S>> choiceToken(final Class<S> clazz) {
            @SuppressWarnings("serial")
            final com.google.common.reflect.TypeToken<ChoiceConfig<S>> choiceToken = new com.google.common.reflect.TypeToken<ChoiceConfig<S>>() {
            }.where(new TypeParameter<S>() {
            }, com.google.common.reflect.TypeToken.of(clazz));

            return (TypeToken<ChoiceConfig<S>>) TypeToken.get(choiceToken.getType());
        }

        private <S> TypeToken<List<ChoiceConfig<S>>> choiceListToken(final Class<S> clazz) {
            @SuppressWarnings("serial")
            final com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>> choiceToken = new com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>>() {
            }.where(new TypeParameter<S>() {
            }, com.google.common.reflect.TypeToken.of(clazz));

            return (TypeToken<List<ChoiceConfig<S>>>) TypeToken.get(choiceToken.getType());
        }
    }.nullSafe();
}

From source file:com.javacreed.examples.gson.part2.AbstractTypeAdapter.java

License:Apache License

protected <E> void delegateWrite(final JsonWriter out, final E object, final Class<E> type) throws IOException {
    final TypeAdapter<E> typeAdapter = gson.getAdapter(type);
    typeAdapter.write(out, object);
}

From source file:com.jd.survey.web.settings.NowwebmanagerController.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w  w  w.j  a v  a  2  s.c  o  m
public void write(JsonWriter out, HibernateProxy value) throws IOException {
    if (value == null) {
        out.nullValue();
        return;
    }
    // Retrieve the original (not proxy) class  
    Class<?> baseType = Hibernate.getClass(value);
    // Get the TypeAdapter of the original class, to delegate the serialization  
    TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
    // Get a filled instance of the original class  
    Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer().getImplementation();
    // Serialize the value  
    delegate.write(out, unproxiedValue);
}

From source file:com.pcloud.sdk.internal.networking.serialization.UnmodifiableListTypeFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, tokenType);

    return new TypeAdapter<T>() {
        @Override// ww w  .  j a  v  a2 s  .  c om
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @SuppressWarnings("unchecked")
        @Override
        public T read(JsonReader arg0) throws IOException {
            T t = delegate.read(arg0);
            if (List.class.isAssignableFrom(tokenType.getRawType())) {
                List<?> list = (List<?>) t;

                return (T) Collections.unmodifiableList(list);
            }

            return t;
        }
    };
}

From source file:com.tinease.tools.json.TypeAdapterRuntimeTypeWrapper.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w  w w  .j  a  v  a 2  s .c o  m
public void write(JsonWriter out, T value) throws IOException {
    // Order of preference for choosing type adapters
    // First preference: a type adapter registered for the runtime type
    // Second preference: a type adapter registered for the declared type
    // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
    // Fourth preference: reflective type adapter for the declared type

    TypeAdapter chosen = delegate;
    Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);
    if (runtimeType != type) {
        TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));
        if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
            // The user registered a type adapter for the runtime type, so we will use that
            chosen = runtimeTypeAdapter;
        } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {
            // The user registered a type adapter for Base class, so we prefer it over the
            // reflective type adapter for the runtime type
            chosen = delegate;
        } else {
            // Use the type adapter for runtime type
            chosen = runtimeTypeAdapter;
        }
    }
    chosen.write(out, value);
}