Search in sources :

Example 16 with TypeAdapter

use of com.google.gson.TypeAdapter in project immutables by immutables.

the class GsonCodecs method typeAdapterFromCodec.

/**
 * Build a TypeAdapter from {@link Codec} opposite of {@link #codecFromTypeAdapter(Class, TypeAdapter)}.
 *
 * @param codec existing codec
 * @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());
        }
    };
}
Also used : AbstractBsonReader(org.bson.AbstractBsonReader) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter)

Example 17 with TypeAdapter

use of com.google.gson.TypeAdapter in project immutables by immutables.

the class Marshaling method toJson.

@SuppressWarnings({ "resource", "unchecked" })
public static String toJson(Object object) {
    TypeAdapter<Object> adapter = GSON.getAdapter((TypeToken<Object>) TypeToken.get(object.getClass()));
    try {
        StringWriter stringWriter = new StringWriter();
        JsonGeneratorWriter writer = new JsonGeneratorWriter(JSON_FACTORY.createGenerator(stringWriter));
        if (adapter instanceof com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.Adapter) {
            throw new IllegalStateException("Immutable adapters not registered");
        }
        GSON.toJson(object, object.getClass(), writer);
        writer.close();
        return stringWriter.toString();
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}
Also used : JsonGeneratorWriter(org.immutables.gson.stream.JsonGeneratorWriter) StringWriter(java.io.StringWriter) TypeAdapter(com.google.gson.TypeAdapter) IOException(java.io.IOException)

Example 18 with TypeAdapter

use of com.google.gson.TypeAdapter in project gocd by gocd.

the class RuntimeTypeAdapterFactory method create.

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }
    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();
            // registration requires that subtype extends T
            @SuppressWarnings("unchecked") 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);
            // registration requires that subtype extends T
            @SuppressWarnings("unchecked") 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();
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) JsonWriter(com.google.gson.stream.JsonWriter) LinkedHashMap(java.util.LinkedHashMap) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 19 with TypeAdapter

use of com.google.gson.TypeAdapter in project Terasology by MovingBlocks.

the class PolymorphicTypeAdapterFactory method create.

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (!baseClass.isAssignableFrom(type.getRawType())) {
        return null;
    }
    return new TypeAdapter<R>() {

        @SuppressWarnings("unchecked")
        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> valueClass = value.getClass();
            String valueTypeName = valueClass.getName();
            TypeToken<?> valueType = TypeToken.get(valueClass);
            TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType);
            if (delegate == null) {
                throw new JsonParseException("Could not serialize " + valueClass.getName());
            }
            JsonElement jsonElement = delegate.toJsonTree(value);
            if (valueClass != baseClass) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonObject clone = new JsonObject();
                clone.add(TYPE_FIELD_NAME, new JsonPrimitive(valueTypeName));
                for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                Streams.write(jsonElement, out);
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            Class<?> valueClass;
            if (jsonElement.isJsonObject()) {
                JsonElement typeNameJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD_NAME);
                if (typeNameJsonElement != null) {
                    String typeName = typeNameJsonElement.getAsString();
                    try {
                        valueClass = Class.forName(typeName);
                    } catch (ClassNotFoundException e) {
                        throw new JsonParseException("Could not find class " + typeName);
                    }
                } else {
                    valueClass = baseClass;
                }
            } else {
                valueClass = baseClass;
            }
            if (!baseClass.isAssignableFrom(valueClass)) {
                throw new JsonParseException(valueClass.getName() + " does not derive from " + baseClass.getName());
            }
            TypeToken<?> valueType = TypeToken.get(valueClass);
            TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType);
            if (delegate == null) {
                throw new JsonParseException("Could not deserialize " + valueClass.getName());
            }
            return delegate.fromJsonTree(jsonElement);
        }
    };
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException) JsonWriter(com.google.gson.stream.JsonWriter) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) Map(java.util.Map)

Example 20 with TypeAdapter

use of com.google.gson.TypeAdapter in project LanternServer by LanternPowered.

the class CatalogTypeTypeAdapterFactory method create.

@Nullable
@Override
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));
        }
    };
}
Also used : CatalogType(org.spongepowered.api.CatalogType) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter) Nullable(javax.annotation.Nullable)

Aggregations

TypeAdapter (com.google.gson.TypeAdapter)23 JsonReader (com.google.gson.stream.JsonReader)16 JsonWriter (com.google.gson.stream.JsonWriter)16 JsonElement (com.google.gson.JsonElement)12 JsonPrimitive (com.google.gson.JsonPrimitive)10 Map (java.util.Map)10 JsonObject (com.google.gson.JsonObject)9 IOException (java.io.IOException)9 JsonParseException (com.google.gson.JsonParseException)8 Type (java.lang.reflect.Type)7 LinkedHashMap (java.util.LinkedHashMap)7 Gson (com.google.gson.Gson)2 TypeToken (com.google.gson.reflect.TypeToken)2 ArrayList (java.util.ArrayList)2 Nullable (javax.annotation.Nullable)2 Reference (ch.aaap.harvestclient.domain.reference.Reference)1 HarvestRuntimeException (ch.aaap.harvestclient.exception.HarvestRuntimeException)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 GsonBuilder (com.google.gson.GsonBuilder)1