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:com.michaelfotiadis.steam.net.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from ww  w  .ja va2 s. c o m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final 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(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // 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?");
                }
                final 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);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }
    };
}

From source file:com.pcloud.sdk.internal.networking.serialization.UnmodifiableListTypeFactory.java

License:Apache License

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

    return new TypeAdapter<T>() {
        @Override/* w  w  w . ja  va 2  s .  c o  m*/
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @SuppressWarnings("unchecked")
        @Override
        public T read(JsonReader arg0) throws IOException {
            T t = delegate.read(arg0);
            if (List.class.isAssignableFrom(tokenType.getRawType())) {
                List<?> list = (List<?>) t;

                return (T) Collections.unmodifiableList(list);
            }

            return t;
        }
    };
}

From source file:com.prayer.vakit.times.gson.RuntimeTypeAdapterFactory.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/* w  ww. j  av  a  2 s  .  com*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
    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:com.scvngr.levelup.core.model.factory.json.PermissionsRequestJsonFactory.java

License:Apache License

@Override
protected void onBuildFactory(@NonNull final GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(PermissionsRequest.State.class,
            new TypeAdapter<PermissionsRequest.State>() {

                @Override/*  w w  w. j  ava 2 s  .c  om*/
                public State read(final JsonReader reader) throws IOException {
                    return State.forString(NullUtils.nonNullContract(reader.nextString()));
                }

                @Override
                public void write(final JsonWriter writer, final State value) throws IOException {
                    writer.value(value.toString());
                }
            });
}

From source file:com.truethat.android.external.gson.RuntimeTypeAdapterFactory.java

License:Apache License

/**
 * This method was modified, to include {@link #typeFieldName} in serialized registered sub types.
 *//* ww  w  . jav  a  2 s . com*/
@Nullable
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType && !labelToSubtype.containsKey(type.getRawType().getSimpleName())) {
        return null;
    }

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
    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 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);
        }

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

From source file:com.twitter.sdk.android.core.models.SafeListAdapter.java

License:Apache License

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

    return new TypeAdapter<T>() {
        @Override/*from  w  w  w  .j av a 2 s .  c  o  m*/
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader arg0) throws IOException {
            final T t = delegate.read(arg0);
            if (List.class.isAssignableFrom(tokenType.getRawType())) {
                if (t == null) {
                    return (T) Collections.EMPTY_LIST;
                }

                final List<?> list = (List<?>) t;
                return (T) Collections.unmodifiableList(list);
            }
            return t;
        }
    };
}

From source file:com.twitter.sdk.android.core.models.SafeMapAdapter.java

License:Apache License

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

    return new TypeAdapter<T>() {
        @Override/*ww  w  .j a  v  a2  s.  co  m*/
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader arg0) throws IOException {
            final T t = delegate.read(arg0);
            if (Map.class.isAssignableFrom(tokenType.getRawType())) {
                if (t == null) {
                    return (T) Collections.EMPTY_MAP;
                }

                final Map<?, ?> map = (Map<?, ?>) t;
                return (T) Collections.unmodifiableMap(map);
            }
            return t;
        }
    };
}

From source file:com.vaadin.addon.charts.model.gsonhelpers.AbstractSeriesTypeAdapterFactory.java

private TypeAdapter<AbstractSeries> customizeMyClassAdapter(Gson gson, TypeToken<AbstractSeries> type) {
    final TypeAdapter<AbstractSeries> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<AbstractSeries>() {
        @Override/*  w w w .  jav a2  s.  c o m*/
        public void write(JsonWriter out, AbstractSeries value) throws IOException {
            JsonObject tree = (JsonObject) delegate.toJsonTree(value);

            // "flatten" series specific plot options at series level. see
            // Higchart API for details
            if (value.getPlotOptions() != null) {
                JsonObject plotOptionsJson = (JsonObject) tree.remove("plotOptions");
                if (plotOptionsJson != null) {
                    Set<Entry<String, JsonElement>> entrySet = plotOptionsJson.entrySet();
                    for (Entry<String, JsonElement> entry : entrySet) {
                        tree.add(entry.getKey(), entry.getValue());
                    }
                    tree.addProperty("type", value.getPlotOptions().getChartType().toString());
                }
            }
            elementAdapter.write(out, tree);
        }

        // This is never used
        @Override
        public AbstractSeries read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            return delegate.fromJsonTree(tree);
        }
    };
}

From source file:com.vaadin.addon.charts.model.gsonhelpers.DataSeriesItemTypeAdapterFactory.java

private TypeAdapter<DataSeriesItem> customizeMyClassAdapter(Gson gson, TypeToken<DataSeriesItem> type) {
    final TypeAdapter<DataSeriesItem> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<DataSeriesItem>() {
        @Override/*from  w  ww .ja  v a 2s.  c  o  m*/
        public void write(JsonWriter out, DataSeriesItem value) throws IOException {
            if (value.isCustomized()) {
                elementAdapter.write(out, delegate.toJsonTree(value));
            } else {
                Number x = value.getX();
                Number y = value.getY();
                if (x != null) {
                    JsonArray jsonArray = new JsonArray();
                    jsonArray.add(new JsonPrimitive(x));
                    if (y != null) {
                        jsonArray.add(new JsonPrimitive(y));
                    } else if (value.getLow() != null) {
                        jsonArray.add(new JsonPrimitive(value.getLow()));
                        jsonArray.add(new JsonPrimitive(value.getHigh()));
                    } else {
                        jsonArray.add(JsonNull.INSTANCE);
                        jsonArray.add(JsonNull.INSTANCE);
                    }
                    elementAdapter.write(out, jsonArray);
                } else {
                    // If no x set, make it like list series, just number or
                    // min-max pairs
                    if (y != null) {
                        elementAdapter.write(out, new JsonPrimitive(y));
                    } else {
                        JsonArray jsonArray = new JsonArray();
                        jsonArray.add(new JsonPrimitive(value.getLow()));
                        jsonArray.add(new JsonPrimitive(value.getHigh()));
                        elementAdapter.write(out, jsonArray);
                    }
                }
            }
        }

        // This is never used
        @Override
        public DataSeriesItem read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            return delegate.fromJsonTree(tree);
        }
    };
}

From source file:com.vaadin.addon.charts.model.gsonhelpers.TitleTypeAdapterFactory.java

private TypeAdapter<Title> customizeMyClassAdapter(Gson gson, TypeToken<Title> type) {
    final TypeAdapter<Title> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<Title>() {
        @Override//from   w  w w.ja  v  a 2 s.  c  o m
        public void write(JsonWriter out, Title value) throws IOException {
            // null for text is significant, else there will be
            // "Chart Title" as default
            if (value != null && value.getText() == null) {
                boolean serializeNulls = out.getSerializeNulls();
                out.setSerializeNulls(true);
                out.beginObject();
                out.name("text");
                out.nullValue();
                out.endObject();
                out.setSerializeNulls(serializeNulls);
            } else {
                elementAdapter.write(out, delegate.toJsonTree(value));
            }
        }

        // This is never used
        @Override
        public Title read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            return delegate.fromJsonTree(tree);
        }
    };
}