Search in sources :

Example 21 with TypeAdapter

use of com.google.gson.TypeAdapter in project edx-app-android by edx.

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 = 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 (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);
        }
    };
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) 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 22 with TypeAdapter

use of com.google.gson.TypeAdapter in project harvest-client by 3AP-AG.

the class ReferenceDtoAdapter method create.

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<? super T> rawType = type.getRawType();
    log.trace("Called create with {}", type);
    if (rawType != Reference.class) {
        return null;
    }
    Class<?> elementClass = parseReferenceType(type);
    String simpleName = elementClass.getSimpleName();
    String expectedClassName = simpleName + DTO_SUFFIX;
    try {
        Class<?> dtoClass = Class.forName(BaseReferenceDto.class.getPackage().getName() + "." + expectedClassName);
        log.trace("Got Dto class {}", dtoClass);
        TypeAdapter<?> delegate = gson.getAdapter(dtoClass);
        log.trace("Returning type adapter for {}", type);
        return new TypeAdapter<T>() {

            @Override
            public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }
                Reference reference = (Reference) value;
                out.value(reference.getId());
            }

            @Override
            @SuppressWarnings("unchecked")
            public T read(JsonReader in) throws IOException {
                return (T) delegate.read(in);
            }
        };
    } catch (ClassNotFoundException e) {
        throw new HarvestRuntimeException("Could not find ReferenceDto. Reference<" + simpleName + "> needs a class named " + expectedClassName + " to existing in the same package as ReferenceDto", e);
    }
}
Also used : HarvestRuntimeException(ch.aaap.harvestclient.exception.HarvestRuntimeException) Reference(ch.aaap.harvestclient.domain.reference.Reference) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter)

Example 23 with TypeAdapter

use of com.google.gson.TypeAdapter in project zeppelin by apache.

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 = jsonElement.getAsJsonObject().remove(typeFieldName);
            String label = (labelJsonElement == null ? null : 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 (jsonObject.has(typeFieldName) && !srcType.getSimpleName().equals("OldInput")) {
                throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            if (!srcType.getSimpleName().equals("OldInput")) {
                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)

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