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:org.terasology.logic.behavior.core.BehaviorTreeBuilder.java

License:Apache License

private void initGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeHierarchyAdapter(BehaviorNode.class, this);
        gsonBuilder.registerTypeAdapterFactory(new UriTypeAdapterFactory());
        gsonBuilder.registerTypeAdapter(BehaviorTree.class, new TypeAdapter<BehaviorTree>() {
            @Override/*from   w  ww . j  a  v  a  2  s. com*/
            public void write(JsonWriter out, BehaviorTree value) throws IOException {
                if (value != null) {
                    // TODO doublecheck URN
                    out.value(value.getUrn().toString());
                } else {
                    out.value("");
                }
            }

            @Override
            public BehaviorTree read(JsonReader in) throws IOException {
                String uri = in.nextString();
                AssetManager assetManager = CoreRegistry.get(AssetManager.class);
                return assetManager.getAsset(new ResourceUrn(uri), BehaviorTree.class).orElse(
                        assetManager.getAsset(new ResourceUrn("Behaviors:fallback"), BehaviorTree.class).get());

            }
        });
        gson = gsonBuilder.create();
    }
}

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;
    }// w  w w .j  a  v a 2s.  com

    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:org.terasology.utilities.gson.CaseInsensitiveEnumTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }/*w ww .ja v  a 2  s  .  co  m*/

    final Map<String, T> lowercaseToConstant = Maps.newHashMap();
    for (T constant : rawType.getEnumConstants()) {
        String lowercase = toLowercase(constant);
        lowercaseToConstant.put(lowercase, constant);
    }

    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                String value = reader.nextString();
                return lowercaseToConstant.get(toLowercase(value));
            }
        }
    };
}

From source file:org.terasology.utilities.gson.UriTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!Uri.class.isAssignableFrom(rawType)) {
        return null;
    }//from  ww w  .jav a  2  s.c  o m

    final Constructor<T> constructor;
    try {
        constructor = rawType.getConstructor(String.class);
        constructor.setAccessible(true);
    } catch (NoSuchMethodException e) {
        logger.error("URI type {} lacks String constructor", rawType);
        return null;
    }

    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            out.value(value.toString());
        }

        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                String nextString = reader.nextString();
                try {
                    return constructor.newInstance(nextString);
                } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                    logger.error("Failed to instantiate uri of type {} from value {}", rawType, nextString, e);
                    return null;
                }
            }
        }
    };
}

From source file:ro.cosu.vampires.server.util.gson.LowercaseEnumTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }//from  w w  w  . j  a  v  a2s  . co  m

    final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                return lowercaseToConstant.get(reader.nextString());
            }
        }
    };
}

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 w  w. ja v 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().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:saulmm.avengers.model.rest.CharacterItemAdapterFactory.java

License:Mozilla Public License

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

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    final TypeAdapter<T> customTypeAdapter = new TypeAdapter<T>() {

        @Override/*from w w w. ja  v  a 2s  .  c  o  m*/
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {

            JsonElement jsonElement = elementAdapter.read(in);

            if (type.getRawType() == saulmm.avengers.model.Character.class)
                return adaptJsonToCharacter(jsonElement, type);

            if (type.getRawType() == List.class)
                return adaptJsonToComic(jsonElement, type);

            return delegate.fromJsonTree(jsonElement);
        }

    }.nullSafe();

    return customTypeAdapter;
}

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  ww w .  j a  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?");
            }

            // 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:uk.ac.stfc.isis.ibex.epics.conversion.json.LowercaseEnumTypeAdapterFactory.java

License:Open Source License

/**
 * {@inheritDoc}/*ww w .  java 2  s.c om*/
 */
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    @SuppressWarnings("unchecked")
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }

    final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                return lowercaseToConstant.get(reader.nextString());
            }
        }
    };
}

From source file:us.blanshard.sudoku.game.GameJson.java

License:Apache License

/**
 * Registers type adapters in the given builder so that history lists and undo
 * stacks can be serialized and deserialized.  Note that undo stacks require a
 * CommandFactory be established before deserialization; see {@link #setFactory}.
 *///from w w  w. j a  va 2s.c o  m
public static GsonBuilder register(GsonBuilder builder) {

    builder.registerTypeHierarchyAdapter(Move.class, new TypeAdapter<Move>() {
        @Override
        public void write(JsonWriter out, Move value) throws IOException {
            out.value(value.toJsonValue());
        }

        @Override
        public Move read(JsonReader in) throws IOException {
            return Move.fromJsonValue(in.nextString());
        }
    });

    final TypeAdapter<Command> commandAdapter = new TypeAdapter<Command>() {
        @Override
        public void write(JsonWriter out, Command value) throws IOException {
            out.value(value.toJsonValue());
        }

        @Override
        public Command read(JsonReader in) throws IOException {
            Iterator<String> values = SPLITTER.split(in.nextString()).iterator();
            String type = values.next();
            return factorySlot.get().toCommand(type, values);
        }
    };
    builder.registerTypeHierarchyAdapter(Command.class, commandAdapter);

    builder.registerTypeAdapter(UndoStack.class, new TypeAdapter<UndoStack>() {
        @Override
        public void write(JsonWriter out, UndoStack value) throws IOException {
            out.beginObject();
            out.name("position").value(value.getPosition());
            out.name("commands").beginArray();
            for (Command c : value.commands)
                commandAdapter.write(out, c);
            out.endArray();
            out.endObject();
        }

        @Override
        public UndoStack read(JsonReader in) throws IOException {
            int position = -1;
            List<Command> commands = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("position")) {
                    position = in.nextInt();
                } else if (name.equals("commands")) {
                    commands = Lists.newArrayList();
                    in.beginArray();
                    while (in.hasNext())
                        commands.add(commandAdapter.read(in));
                    in.endArray();
                } else {
                    in.skipValue();
                }
            }
            in.endObject();
            return new UndoStack(commands, position);
        }
    });

    return builder;
}