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:de.symeda.sormas.app.rest.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from www.  ja  va  2 s. 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;
            if (maintainType) {
                labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            } else {
                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 (maintainType) {
                Streams.write(jsonObject, out);
                return;
            }

            JsonObject clone = new JsonObject();

            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            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:edu.mit.media.funf.config.ContextInjectorTypeAdapaterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final TypeAdapter<T> delegateAdapter = delegate.create(gson, type);
    if (delegateAdapter == null) {
        return null;
    } else {/*  www.  j ava 2 s .c  o m*/
        return new TypeAdapter<T>() {

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

            @Override
            public T read(JsonReader in) throws IOException {
                T value = delegateAdapter.read(in);
                if (value != null) {
                    try {
                        Field contextField = AnnotationUtil.getField(CONTEXT_FIELD, value.getClass());
                        if (contextField != null && Context.class.isAssignableFrom(contextField.getType())) {
                            boolean isAccessible = contextField.isAccessible();
                            contextField.setAccessible(true);
                            contextField.set(value, context);
                            contextField.setAccessible(isAccessible);
                        }
                    } catch (SecurityException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    } catch (IllegalArgumentException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    } catch (IllegalAccessException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    }
                }
                return value;
            }
        };
    }
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    if (baseClass.isAssignableFrom(type.getRawType())) {
        return new TypeAdapter<T>() {
            @Override//from w  ww  .  j  a v  a  2s .  co  m
            public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter delegate = delegateFactory.create(gson, TypeToken.get(value.getClass()));
                JsonTreeWriter treeWriter = new JsonTreeWriter();
                delegate.write(treeWriter, value);
                JsonElement el = treeWriter.get();

                if (el.isJsonObject()) {
                    JsonObject elObject = el.getAsJsonObject();
                    elObject.addProperty(RuntimeTypeAdapterFactory.TYPE, value.getClass().getName());
                    Streams.write(elObject, out);
                } else {
                    Streams.write(el, out);
                }
            }

            @Override
            public T read(JsonReader in) throws IOException {
                // TODO: need to handle null
                JsonElement el = Streams.parse(in);
                Class<? extends T> runtimeType = getRuntimeType(el, type);
                if (runtimeType == null) {
                    throw new ParseException("RuntimeTypeAdapter: Unable to parse runtime type.");
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter<? extends T> delegate = delegateFactory.create(gson,
                        TypeToken.get(runtimeType));

                if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
                    JsonObject typeObject = new JsonObject();
                    typeObject.addProperty(TYPE, el.getAsString());
                    el = typeObject;
                }

                return delegate.read(new JsonTreeReader(el));
            }

        };
    }
    return null;
}

From source file:edu.mit.media.funf.config.ListenerInjectorTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegateAdapter = delegate.create(gson, type);
    if (delegateAdapter == null) {
        return null;
    } else {//from   w w w .  ja  v  a  2s .  c o m
        return new TypeAdapter<T>() {

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

            @Override
            public T read(JsonReader in) throws IOException {
                T value = delegateAdapter.read(in);
                if (value != null && value instanceof DataSource) {
                    try {
                        Field filtersField = AnnotationUtil.getField(ConfigRewriteUtil.FILTER_FIELD_NAME,
                                value.getClass());
                        Field delegatorField = AnnotationUtil.getField(ConfigRewriteUtil.DELEGATOR_FIELD_NAME,
                                value.getClass());
                        boolean isDelegatorAccessible = delegatorField.isAccessible();
                        delegatorField.setAccessible(true);
                        DataListener delegator = (DataListener) delegatorField.get(value);
                        if (filtersField != null && delegator != null) {
                            boolean isAccessible = filtersField.isAccessible();
                            filtersField.setAccessible(true);
                            Object existingFilter = filtersField.get(value);
                            if (existingFilter == null)
                                filtersField.set(value, delegator);
                            else
                                injectListener(existingFilter, delegator);
                            filtersField.setAccessible(isAccessible);
                        }
                        delegatorField.setAccessible(isDelegatorAccessible);
                    } catch (SecurityException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    } catch (IllegalArgumentException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    } catch (IllegalAccessException e) {
                        // Swallow
                        Log.v(TAG, e.getMessage());
                    }
                }
                return value;
            }

            private void injectListener(Object value, DataListener listener) {

                try {
                    Field listenerField = AnnotationUtil.getField(ConfigRewriteUtil.LISTENER_FIELD_NAME,
                            value.getClass());
                    if (listenerField != null && DataListener.class.isAssignableFrom(listenerField.getType())) {
                        boolean isAccessible = listenerField.isAccessible();
                        listenerField.setAccessible(true);
                        Object existingListener = listenerField.get(value);
                        if (existingListener == null)
                            listenerField.set(existingListener, listener);
                        else
                            injectListener(existingListener, listener);
                        listenerField.setAccessible(isAccessible);
                        return;
                    }
                } catch (SecurityException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                } catch (IllegalArgumentException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                } catch (IllegalAccessException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                }

                try {
                    Field targetField = AnnotationUtil.getField(ConfigRewriteUtil.TARGET_FIELD_NAME,
                            value.getClass());
                    if (targetField != null) {
                        boolean isAccessible = targetField.isAccessible();
                        targetField.setAccessible(true);
                        Object existingTarget = targetField.get(value);
                        if (existingTarget != null)
                            injectListener(existingTarget, listener);
                        targetField.setAccessible(isAccessible);
                        return;
                    }
                } catch (SecurityException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                } catch (IllegalArgumentException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                } catch (IllegalAccessException e) {
                    // Swallow
                    Log.v(TAG, e.getMessage());
                }

                if (value instanceof DataSource) {
                    ((DataSource) value).setListener(listener);
                    return;
                }
            }

        };
    }
}

From source file:funf.config.ContextInjectorTypeAdapaterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final TypeAdapter<T> delegateAdapter = delegate.create(gson, type);
    if (delegateAdapter == null) {
        return null;
    } else {/*from  w ww.  ja  va2s . c o  m*/
        return new TypeAdapter<T>() {

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

            @Override
            public T read(JsonReader in) throws IOException {
                T value = delegateAdapter.read(in);
                if (value != null) {
                    try {
                        Field contextField = AnnotationUtil.getField(CONTEXT_FIELD, value.getClass());
                        if (contextField != null && Context.class.isAssignableFrom(contextField.getType())) {
                            boolean isAccessible = contextField.isAccessible();
                            contextField.setAccessible(true);
                            contextField.set(value, context);
                            contextField.setAccessible(isAccessible);
                        }
                    } catch (SecurityException e) {
                        // Swallow
                        Log.v(LogUtil.TAG, e.getMessage());
                    } catch (IllegalArgumentException e) {
                        // Swallow
                        Log.v(LogUtil.TAG, e.getMessage());
                    } catch (IllegalAccessException e) {
                        // Swallow
                        Log.v(LogUtil.TAG, e.getMessage());
                    }
                }
                return value;
            }
        };
    }
}

From source file:io.hops.hopsworks.api.zeppelin.json.NotebookTypeAdapterFactory.java

License:Apache License

private TypeAdapter<C> customizeTypeAdapter(Gson gson, TypeToken<C> type) {
    final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<C>() {
        @Override//from w  w w . ja v  a 2  s .co  m
        public void write(JsonWriter out, C value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        @Override
        public C read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
        }
    };
}

From source file:io.prediction.workflow.JavaQueryTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType().equals(JavaQuery.class)) {
        return (TypeAdapter<T>) new TypeAdapter<JavaQuery>() {
            public void write(JsonWriter out, JavaQuery value) throws IOException {
                if (value == null) {
                    out.nullValue();//ww w .  ja va2s.  c  o m
                } else {
                    out.beginObject();
                    out.name("q").value(value.getQ().toUpperCase());
                    out.endObject();
                }
            }

            public JavaQuery read(JsonReader reader) throws IOException {
                if (reader.peek() == JsonToken.NULL) {
                    reader.nextNull();
                    return null;
                } else {
                    reader.beginObject();
                    reader.nextName();
                    String q = reader.nextString();
                    reader.endObject();
                    return new JavaQuery(q.toUpperCase());
                }
            }
        };
    } else {
        return null;
    }
}

From source file:jp.pay.model.ExternalAccountTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!ExternalAccount.class.isAssignableFrom(type.getRawType())) {
        return null; // this class only serializes 'ExternalAccount' and its subtypes
    }/*from w  ww  .  ja  v a  2 s .com*/

    final String SOURCE_OBJECT_PROP = "object";

    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    final TypeAdapter<ExternalAccount> externalAccountAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(ExternalAccount.class));

    final TypeAdapter<Card> cardAdapter = gson.getDelegateAdapter(this, TypeToken.get(Card.class));

    TypeAdapter<ExternalAccount> result = new TypeAdapter<ExternalAccount>() {
        public void write(JsonWriter out, ExternalAccount value) throws IOException {
            // TODO: check instance of for correct writer
            externalAccountAdapter.write(out, value);
        }

        public ExternalAccount read(JsonReader in) throws IOException {
            JsonObject object = elementAdapter.read(in).getAsJsonObject();
            String sourceObject = object.getAsJsonPrimitive(SOURCE_OBJECT_PROP).getAsString();

            if (sourceObject.equals("card")) {
                return cardAdapter.fromJsonTree(object);
            } else {
                return externalAccountAdapter.fromJsonTree(object);
            }
        }
    }.nullSafe();

    return (TypeAdapter<T>) result;
}

From source file:jp.yokomark.utils.gson.adapter.EnumTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  w  w w  . j a va2 s .  c o m*/
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    final Class<? super T> rawType = type.getRawType();
    if (!rawType.isEnum()) { // not an enum type, so do not create any of adapter.
        return null;
    }

    final Map<String, T> jsonNameToInstance = new HashMap<String, T>();
    for (T constant : (T[]) rawType.getEnumConstants()) {
        jsonNameToInstance.put(constantNameToJsonName(((Enum<?>) constant).name()), constant);
    }

    return (new TypeAdapter<T>() {

        @Override
        public T read(final JsonReader reader) throws IOException {
            final String constValue = reader.nextString();
            return jsonNameToInstance.get(constValue);
        }

        @Override
        public void write(final JsonWriter writer, T constant) throws IOException {
            writer.value(constantNameToJsonName(((Enum<?>) constant).name()));
        }
    }).nullSafe();
}

From source file:leafcutter.client.Serializer.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.c o 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().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();
}