Example usage for com.google.gson Gson getDelegateAdapter

List of usage examples for com.google.gson Gson getDelegateAdapter

Introduction

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

Prototype

public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) 

Source Link

Document

This method is used to get an alternate type adapter for the specified type.

Usage

From source file:org.lanternpowered.server.script.function.value.json.FloatValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected FloatValueProvider deserialize(TypeToken<FloatValueProvider> type, JsonElement element, Gson gson) {
    final Class<? super FloatValueProvider> raw = type.getRawType();
    if (FloatValueProvider.Constant.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(FloatValueProvider.Constant.class))
                .fromJsonTree(element);//from ww  w. j  a va 2  s  . c o  m
    } else if (FloatValueProvider.Range.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(FloatValueProvider.Range.class))
                .fromJsonTree(element);
    } else if (raw == FloatValueProvider.class) {
        // The actual condition type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonPrimitive()) {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, FloatValueProvider.class).get();
            }
            return gson.getDelegateAdapter(this, TypeToken.get(FloatValueProvider.Constant.class))
                    .fromJsonTree(element);
        }
    }
    return super.deserialize(type, element, gson);
}

From source file:org.lanternpowered.server.script.function.value.json.IntValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected JsonElement serialize(TypeToken<IntValueProvider> type, IntValueProvider value, Gson gson)
        throws IOException {
    if (value instanceof IntValueProvider.Range) {
        return gson.getDelegateAdapter(this, TypeToken.get(IntValueProvider.Range.class))
                .toJsonTree((IntValueProvider.Range) value);
    } else if (value instanceof IntValueProvider.Constant) {
        return gson.getDelegateAdapter(this, TypeToken.get(IntValueProvider.Constant.class))
                .toJsonTree((IntValueProvider.Constant) value);
    } else if (value instanceof ScriptFunction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ScriptFunction.class))
                .toJsonTree((ScriptFunction) value);
    }//from  ww w .jav a2s  . c o m
    return super.serialize(type, value, gson);
}

From source file:org.lanternpowered.server.script.function.value.json.IntValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected IntValueProvider deserialize(TypeToken<IntValueProvider> type, JsonElement element, Gson gson) {
    final Class<? super IntValueProvider> raw = type.getRawType();
    if (IntValueProvider.Constant.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(IntValueProvider.Constant.class))
                .fromJsonTree(element);/* w  ww  . java 2s . com*/
    } else if (IntValueProvider.Range.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(IntValueProvider.Range.class)).fromJsonTree(element);
    } else if (raw == IntValueProvider.class) {
        // The actual condition type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonPrimitive()) {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, IntValueProvider.class).get();
            }
            return gson.getDelegateAdapter(this, TypeToken.get(IntValueProvider.Constant.class))
                    .fromJsonTree(element);
        }
    }
    return super.deserialize(type, element, gson);
}

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

License:MIT License

protected JsonElement serialize(TypeToken<V> type, V value, Gson gson) throws IOException {
    //noinspection unchecked
    final Optional<O> optType = this.registry.getByClass((Class) value.getClass());
    if (!optType.isPresent()) {
        throw new IOException(
                "Attempted to serialize a action type that is not registered: " + value.getClass().getName());
    }/*from w  w  w. j  a v a2  s.  c o m*/
    final JsonObject json = new JsonObject();
    json.addProperty(TYPE, optType.get().getId());
    //noinspection unchecked
    final TypeAdapter<V> delegateTypeAdapter = gson.getDelegateAdapter(this,
            (TypeToken<V>) TypeToken.get(optType.get().getType()));
    json.add(DATA, delegateTypeAdapter.toJsonTree(value));
    return json;
}

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

License:MIT License

protected V deserialize(TypeToken<V> type, JsonElement element, Gson gson) {
    final JsonObject obj = element.getAsJsonObject();
    final String valueTypeId = obj.get(TYPE).getAsString();
    //noinspection unchecked
    final Optional<O> optType = this.registry.getById(valueTypeId);
    if (!optType.isPresent()) {
        throw new IllegalStateException("Unknown type id: " + valueTypeId);
    }//w w  w.  ja v  a2s  .  co m
    //noinspection unchecked
    final TypeAdapter<V> delegateTypeAdapter = gson.getDelegateAdapter(this,
            (TypeToken<V>) TypeToken.get(optType.get().getType()));
    try {
        return delegateTypeAdapter.fromJsonTree(obj.get(DATA));
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to compile the " + this.typeToken.toString() + " from the json: " + obj.toString(), e);
    }
}

From source file:org.mule.runtime.extension.internal.persistence.DefaultImplementationTypeAdapterFactory.java

License:Open Source License

/**
 * @param gson                  The actual Gson serializer
 * @param type                  Implementation that GSON is trying to find a {@link TypeAdapter}
 * @param <C> type of objects that the {@link TypeAdapter} will create
 * @return if {@param type} is subclass of {@link #superClass} a {@link TypeAdapter}, that serializes and deserialize
 * {@link C} instances//from   w  w w  .j  a va2  s  . c o  m
 */
@Override
public <C> TypeAdapter<C> create(Gson gson, TypeToken<C> type) {
    if (superClass.isAssignableFrom(type.getRawType())) {
        return gson.getDelegateAdapter(this, TypeToken.get((Class<C>) clazz));
    }
    return null;
}

From source file:org.mule.runtime.extension.internal.persistence.RestrictiveTypeAdapterFactory.java

License:Open Source License

/**
 * @param gson The actual Gson serializer
 * @param type Implementation that GSON is trying to find a {@link TypeAdapter}
 * @param <T>  type of objects that the {@link TypeAdapter} will create
 * @return if {@param type} is a {@link #clazz} a {@link TypeAdapter}, that serializes and deserialize
 * {@link T} instances//from   w ww  . ja v a2  s.c  o  m
 */
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (clazz.equals(type.getRawType())) {
        return gson.getDelegateAdapter(this, TypeToken.get((Class<T>) implementationClazz));
    }
    return null;
}

From source file:org.objectpocket.gson.CustomTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

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

    // @Entity//from  w  w  w  .  j a v a  2 s  . c o m
    if (type.getRawType().getAnnotation(Entity.class) != null) {
        return new TypeAdapter<T>() {

            // SERIALIZE
            public void write(JsonWriter out, T obj) throws IOException {
                if (obj != null) {
                    String id = objectPocket.getIdForObject(obj);
                    // normalize
                    if (!objectPocket.isSerializeAsRoot(obj)) {
                        gson.toJson(new ProxyOut(obj.getClass().getTypeName(), id), ProxyOut.class, out);
                        return;
                    } else {
                        objectPocket.setSerializeAsRoot(obj, false);
                    }
                }
                // default serialization
                delegate.write(out, obj);
            };

            // DESERIALIZE
            @SuppressWarnings("unchecked")
            @Override
            public T read(JsonReader in) throws IOException {
                if (in.getPath().length() > 2) {
                    in.beginObject();
                    in.nextName();
                    StringBuilder sb = new StringBuilder(in.nextString());
                    String id = sb.substring(0, sb.indexOf("@"));
                    in.endObject();
                    T obj = null;
                    try {
                        obj = (T) ReflectionUtil.instantiateDefaultConstructor(type.getRawType());
                    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException
                            | NoSuchMethodException | InvocationTargetException e) {
                        throw new IOException("Could not instantiate class " + type.getRawType().getName()
                                + "\n" + "Might be that the class has no default constructor!", e);
                    }
                    objectPocket.addIdFromReadObject(obj, id);
                    return obj;
                } else {
                    T obj = delegate.read(in);
                    return obj;
                }
            }
        };
    }
    // All other
    else {
        return delegate;
    }
}

From source file:org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory.java

License:Open Source License

/**
 * Handle {@link BaseChannelConfiguration}
 *
 * @param gson//from ww  w .  j  a  v  a  2 s. c o m
 * @param type
 * @return
 */
private <T> TypeAdapter<T> createHAConfig(Gson gson, TypeToken<T> type) {
    /* The delegate is the 'default' adapter */
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {
        @Override
        public T read(@Nullable JsonReader in) throws IOException {
            if (in == null) {
                return null;
            }
            /* read the object using the default adapter, but translate the names in the reader */
            T result = delegate.read(MappingJsonReader.getConfigMapper(in));
            /* do the '~' expansion afterwards */
            expandTidleInTopics(BaseChannelConfiguration.class.cast(result));
            return result;
        }

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

From source file:org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory.java

License:Open Source License

private <T> TypeAdapter<T> createHADevice(Gson gson, TypeToken<T> type) {
    /* The delegate is the 'default' adapter */
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {
        @Override/*w ww .ja  v a  2 s  .  c  o  m*/
        public T read(@Nullable JsonReader in) throws IOException {
            if (in == null) {
                return null;
            }
            /* read the object using the default adapter, but translate the names in the reader */
            T result = delegate.read(MappingJsonReader.getDeviceMapper(in));
            return result;
        }

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