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:me.albinmathew.celluloid.api.http.ItemTypeAdapterFactory.java

License:Apache License

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

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

    return new TypeAdapter<T>() {

        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);//from   ww  w.j  a  va  2s .c  o m
        }

        public T read(JsonReader in) throws IOException {

            JsonElement jsonElement = elementAdapter.read(in);
            return delegate.fromJsonTree(jsonElement);
        }
    }.nullSafe();
}

From source file:mobi.tattu.utils.persistance.datastore.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (!baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }//from  ww w . java  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 configure a subtype?");
            }
            try {
                return delegate.fromJsonTree(jsonElement);
            } catch (JsonSyntaxException e) {
                return null;
            }
        }

        @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 configure 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:mx.openpay.client.serialization.OpenpayTypeAdapterFactory.java

License:Apache License

public TypeAdapter<C> getClassAdapter(final Gson gson, final TypeToken<C> type) {
    final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<C>() {

        @Override//w ww .j  av  a  2  s . c o  m
        public void write(final JsonWriter out, final C value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            OpenpayTypeAdapterFactory.this.beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        @Override
        public C read(final JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            OpenpayTypeAdapterFactory.this.afterRead(tree);
            return delegate.fromJsonTree(tree);
        }
    };
}

From source file:net.billforward.gson.typeadapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from w w w .  jav a 2s.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) {
                delegate = (TypeAdapter<R>) labelToDelegate.get("default_value_mapping");
            }
            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);
        }
    };
}

From source file:net.chris54721.infinitycubed.utils.LowercaseEnumTypeAdapterFactory.java

License:Apache License

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

    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:net.daporkchop.toobeetooteebot.text.EnumTypeAdapterFactory.java

License:Open Source License

public <T> TypeAdapter<T> create(Gson p_create_1_, TypeToken<T> p_create_2_) {
    Class<T> oclass = (Class<T>) p_create_2_.getRawType();

    if (!oclass.isEnum()) {
        return null;
    } else {/*from   w  w w . j a v a 2  s.c o  m*/
        final Map<String, T> map = Maps.newHashMap();

        for (T t : oclass.getEnumConstants()) {
            map.put(this.getName(t), t);
        }

        return new TypeAdapter<T>() {
            public void write(JsonWriter p_write_1_, T p_write_2_) throws IOException {
                if (p_write_2_ == null) {
                    p_write_1_.nullValue();
                } else {
                    p_write_1_.value(EnumTypeAdapterFactory.this.getName(p_write_2_));
                }
            }

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

From source file:net.feed_the_beast.launcher.json.EnumAdaptorFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  www  . jav a 2  s. com*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum()) {
        return null;
    }
    final Map<String, T> map = Maps.newHashMap();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null) {
                return null;
            }
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:net.friendscraft_2_launch.launcher.json.EnumAdaptorFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from ww w. j av a2 s. c o m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum())
        return null;
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null)
                return null;
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:net.minecrell.workbench.tools.util.gson.LowerCaseEnumTypeAdapterFactory.java

License:Open Source License

@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;
    }/*  www  .j av a 2  s.  co m*/

    final Map<String, T> lookup = new HashMap<>();
    for (T constant : rawType.getEnumConstants()) {
        lookup.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 lookup.get(reader.nextString());
            }
        }
    };
}

From source file:net.segoia.event.eventbus.config.json.EventBusJsonConfigLoader.java

License:Apache License

public static EventBusJsonConfig load(Reader reader) {
    GsonBuilder gb = new GsonBuilder();

    gb.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

        @Override/*from  w  w w .  j  a v a  2s .  com*/
        public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jo = json.getAsJsonObject();
            JsonElement conditionType = jo.get("ctype");
            String ctype = null;
            if (conditionType != null) {
                ctype = conditionType.getAsString().trim();
                if ("".equals(ctype)) {
                    ctype = null;
                }
            }
            JsonDeserializer<?> deserializerForType = jsonDeserializers.get(ctype);
            if (deserializerForType == null) {
                throw new JsonParseException("No deserializer defined for condition type " + ctype);
            }
            return (Condition) deserializerForType.deserialize(json, typeOfT, context);
        }
    });

    gb.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
            final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);

            TypeAdapter<T> typeAdapter = new TypeAdapter<T>() {

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

                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement value = Streams.parse(in);

                    if (value.isJsonNull()) {
                        return null;
                    }

                    if (!value.isJsonObject()) {
                        return delegateAdapter.fromJsonTree(value);
                    }
                    // System.out.println(value+" "+value.getClass());
                    JsonObject jo = value.getAsJsonObject();

                    JsonElement cnameElem = jo.remove("className");

                    if (cnameElem != null) {
                        String cname = cnameElem.getAsString();

                        try {
                            // System.out.println("using clazz " + cname);
                            return (T) gson.fromJson(value, Class.forName(cname));
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                    } else {
                        return delegateAdapter.fromJsonTree(value);
                    }
                }
            };

            return typeAdapter;

        }
    });

    final Gson gson = gb.create();

    EventBusJsonConfig ebusConfig = gson.fromJson(reader, EventBusJsonConfig.class);

    return ebusConfig;
}