Example usage for com.google.gson TypeAdapter toJsonTree

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

Introduction

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

Prototype

public final JsonElement toJsonTree(T value) 

Source Link

Document

Converts value to a JSON tree.

Usage

From source file:org.apache.zeppelin.display.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*  ww  w .  j av a 2 s.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);
            String label = (labelJsonElement == null ? null : 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) && !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();
}

From source file:org.codice.admin.router.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }//from  w  w w .j a v  a 2  s. com

    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();
}

From source file:org.diorite.config.serialization.Serialization.java

License:Open Source License

@SuppressWarnings("unchecked")
<T> Object serialize(Class<T> type, T object, SerializationType serializationType,
        @Nullable DocumentComments comments) {
    if (isSimple(object)) {
        return object;
    }// w  w w.j  ava 2 s  .  c  om
    if (!this.isSerializable(type)) {
        if (this.canBeSerialized(type)) {
            if (serializationType == SerializationType.YAML) {
                return this.fromYaml(this.toYaml(object), Map.class);
            } else {
                TypeAdapter<T> typeAdapter = this.gson().getAdapter(type);
                return this.fromJson(typeAdapter.toJsonTree(object), Map.class);
            }
        }
        throw new IllegalArgumentException(
                "Given object isn't serializable: (" + type.getName() + ") -> " + object);
    }
    SimpleSerializationData serializationData = (SimpleSerializationData) SerializationData
            .create(serializationType, this, type);
    if (comments != null) {
        serializationData.setComments(comments);
    }

    ((Serializer<T>) this.serializerMap.get(type)).serialize(object, serializationData);
    return serializationData.rawValue();
}

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 av  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.syphr.lametrictime.api.common.impl.typeadapters.imported.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from   www .  j  a v  a2  s.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 = RuntimeTypeAdapterFactory.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());
            }
            RuntimeTypeAdapterFactory.write(clone, out);
        }
    }.nullSafe();
}

From source file:org.terasology.persistence.typeHandling.gson.PolymorphicTypeAdapterFactory.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (!baseClass.isAssignableFrom(type.getRawType())) {
        return null;
    }//from   w  w  w  .  j av  a  2s .  c  om

    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);
        }
    };
}

From source file:ru.teamrocket.csrsysteamdesktop.Service.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }//w  ww .jav  a2 s.com

    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().get(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();
}

From source file:se.joelpet.android.toyreaderforreddit.gson.typeadapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from www.j  a 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 = 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?");
            }

            // joep: take the "data" jsonElement
            return delegate.fromJsonTree(jsonElement.getAsJsonObject().remove("data"));
        }

        @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);
        }
    };
}

From source file:zardoni.matteo.SerializzazioneTimeline.test.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from  w  ww  . ja  va  2 s .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();
}