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.cyanogenmod.account.gcm.model.MessageTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!Message.class.isAssignableFrom(type.getRawType())) {
        return null;
    }/*from  w  ww  .  j  a v  a2  s .c o m*/

    final TypeAdapter<Message> rootAdapter = gson.getDelegateAdapter(this, TypeToken.get(Message.class));
    final TypeAdapter<PublicKeyMessage> keyExchangeAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(PublicKeyMessage.class));
    final TypeAdapter<SymmetricKeyMessage> symmetricKeyAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(SymmetricKeyMessage.class));
    final TypeAdapter<EncryptedMessage> secureMessageAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(EncryptedMessage.class));
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    TypeAdapter<Message> result = new TypeAdapter<Message>() {
        @Override
        public void write(JsonWriter out, Message value) throws IOException {
            if (value instanceof PublicKeyMessage) {
                keyExchangeAdapter.write(out, (PublicKeyMessage) value);
            } else if (value instanceof SymmetricKeyMessage) {
                symmetricKeyAdapter.write(out, (SymmetricKeyMessage) value);
            } else if (value instanceof EncryptedMessage) {
                secureMessageAdapter.write(out, (EncryptedMessage) value);
            } else {
                JsonObject object = rootAdapter.toJsonTree(value).getAsJsonObject();
                elementAdapter.write(out, object);
            }
        }

        @Override
        public Message read(JsonReader in) throws IOException {
            JsonObject object = elementAdapter.read(in).getAsJsonObject();
            if (object.has("public_key")) {
                return keyExchangeAdapter.fromJsonTree(object);
            } else if (object.has("symmetric_key")) {
                return symmetricKeyAdapter.fromJsonTree(object);
            } else if (object.has("ciphertext")) {
                return secureMessageAdapter.fromJsonTree(object);
            } else {
                return rootAdapter.fromJsonTree(object);
            }
        }
    }.nullSafe();

    return (TypeAdapter<T>) result;
}

From source file:com.dell.prototype.apm.model.javaee.ApplicationServer.java

License:Open Source License

@Override
public String toString() {

    return new GsonBuilder().setPrettyPrinting()
            .registerTypeAdapter(this.getClass(), new TypeAdapter<ApplicationServer>() {
                private String getFormattedRequests(List<Request> requests) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("[");
                    for (int i = 0; i < requests.size(); i++) {
                        sb.append("request sequence " + i + ": ");
                        sb.append(requests.get(i));
                    }//w  ww .j  a  v  a  2  s  .  c  o m
                    sb.append("]");
                    return sb.toString();
                }

                @Override
                public void write(JsonWriter jsonWriter, ApplicationServer applicationServer)
                        throws IOException {
                    jsonWriter.beginObject();
                    jsonWriter.name("name").value(applicationServer.getName());
                    jsonWriter.name("jvm").value(
                            applicationServer.getJvm() == null ? "" : applicationServer.getJvm().toString());
                    jsonWriter.name("responseTime").value(applicationServer.getResponseTime().toString());
                    jsonWriter.name("requests").value(getFormattedRequests(applicationServer.getRequests()));
                    jsonWriter.endObject();
                }

                @Override
                public ApplicationServer read(JsonReader jsonReader) throws IOException {
                    return null;
                }
            }).create().toJson(this);
}

From source file:com.dell.prototype.apm.model.javaee.JVM.java

License:Open Source License

@Override
public String toString() {
    return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(this.getClass(), new TypeAdapter<JVM>() {
        @Override//from  w ww  .ja v a 2 s.  c  om
        public void write(JsonWriter jsonWriter, JVM jvm) throws IOException {
            jsonWriter.beginObject();
            jsonWriter.name("name").value(jvm.getName());
            jsonWriter.name("version").value(jvm.getVersion());
            jsonWriter.name("architecture").value(jvm.getArchitecture());
            jsonWriter.name("usedHeap").value(jvm.getUsedHeap().toString());
            jsonWriter.name("committedHeap").value(jvm.getCommittedHeap().toString());
            jsonWriter.name("gcOverhead").value(jvm.getGcOverhead().toString());
            jsonWriter.name("threadsCount").value(jvm.getThreadsCount().toString());
            jsonWriter.name("avgThreadCpuTime").value(jvm.getAvgThreadCpuTime().toString());
            jsonWriter.endObject();
        }

        @Override
        public JVM read(JsonReader jsonReader) throws IOException {
            return null;
        }
    }).create().toJson(this);
}

From source file:com.dell.prototype.apm.model.Metric.java

License:Open Source License

@Override
public String toString() {
    return new GsonBuilder().registerTypeAdapter(this.getClass(), new TypeAdapter<Metric>() {
        @Override/*from   w ww  .  j a  v  a 2s .  co m*/
        public void write(JsonWriter jsonWriter, Metric metric) throws IOException {
            jsonWriter.beginObject();
            jsonWriter.name("name").value(metric.getName());
            List<MetricValue> values = metric.getValues();
            if (values.size() > 0) {
                jsonWriter.name("latestValue").value(values.get(values.size() - 1).toString());
            } else {
                jsonWriter.name("latestValue").value("");
            }
            jsonWriter.endObject();
        }

        @Override
        public Metric read(JsonReader jsonReader) throws IOException {
            return null;
        }
    }).setPrettyPrinting().create().toJson(this);
}

From source file:com.devicehive.json.adapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*  w ww  . j  a va2s  .  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);
            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);
            Streams.write(jsonObject, out);
        }
    }.nullSafe();
}

From source file:com.drakeet.rebase.api.tool.ResponseTypeAdapterFactory.java

License:Open Source License

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

    return new TypeAdapter<T>() {
        @Override//from w ww.java  2 s .co m
        public void write(JsonWriter out, T value) throws IOException {
            delegateAdapter.write(out, value);
        }

        @Override
        @SuppressWarnings("PointlessBooleanExpression")
        public T read(JsonReader in) throws IOException {
            JsonElement jsonElement = jsonElementAdapter.read(in);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has(ERROR) && jsonObject.get(ERROR).getAsBoolean() == false) {
                    if (jsonObject.has(DATA) && isJson(jsonObject, DATA)) {
                        jsonElement = jsonObject.get(DATA);
                    }
                }
            }
            return delegateAdapter.fromJsonTree(jsonElement);
        }
    }.nullSafe();
}

From source file:com.etermax.conversations.repository.impl.elasticsearch.mapper.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  .java2 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();
}

From source file:com.flipkart.batching.gson.RuntimeTypeAdapterFactory.java

License:Open Source License

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

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

    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = labelToTypeAdapter.get(entry.getKey());
        if (delegate == null) {
            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 reader) throws IOException {

            if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
                reader.skipValue();
                return null;
            }
            reader.beginObject();

            String label = null;
            R result = null;
            while (reader.hasNext()) {
                String name = reader.nextName();
                com.google.gson.stream.JsonToken jsonToken = reader.peek();
                if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
                    reader.skipValue();
                    continue;
                }
                switch (name) {
                case "type":
                    label = TypeAdapters.STRING.read(reader);
                    break;
                case "value":
                    @SuppressWarnings("unchecked") // registration requires that subtype extends T
                    TypeAdapter<R> delegate = label == null ? null
                            : (TypeAdapter<R>) labelToDelegate.get(label);
                    if (delegate == null) {
                        throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
                                + label + "; did you forget to register a subtype?");
                    }
                    result = delegate.read(reader);
                    break;
                default:
                    reader.skipValue();
                    break;
                }
            }

            reader.endObject();
            return result;
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            @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?");
            }
            String label = subtypeToLabel.get(srcType);
            out.beginObject();

            out.name("type");
            out.value(label);

            out.name("value");
            delegate.write(out, value);

            out.endObject();
        }
    }.nullSafe();
}

From source file:com.github.gfx.android.orma.gson.SingleAssociationTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> typeToken) {
    if (!typeToken.getRawType().isAssignableFrom(SingleAssociation.class)) {
        return null;
    }//from   ww  w .ja  v  a2s  .  c  o  m
    if (!(typeToken.getType() instanceof ParameterizedType)) {
        throw new ClassCastException(
                "Expected a parameterized SingleAssociation<T>, but got " + typeToken.getType());
    }

    final Class<?> modelType = (Class<?>) ((ParameterizedType) typeToken.getType()).getActualTypeArguments()[0];

    final Schema<?> schema = Schemas.get(modelType);

    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            SingleAssociation<?> association = (SingleAssociation<?>) value;
            gson.toJson(association.get(), modelType, out);
        }

        @Override
        @SuppressWarnings("unchecked")
        public T read(JsonReader in) throws IOException {
            Object model = gson.fromJson(in, modelType);
            return (T) SingleAssociation.just((Schema<Object>) schema, model);
        }
    };
}

From source file:com.github.kyriosdata.regras.infraestrutura.CustomRegraTypeAdapterFactory.java

License:Creative Commons License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    if (type.getRawType() != Regra.class)
        return null;

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

    return new TypeAdapter<T>() {
        @Override/*from  w w  w. j  a  v  a  2 s  . co m*/
        public void write(final JsonWriter jsonWriter, final T t) throws IOException {
            jsonWriter.beginObject();
            jsonWriter.name("tipo");
            jsonWriter.value(getTipo(t.getClass().getName()));
            jsonWriter.name("obj");
            delegate.write(jsonWriter, t);
            jsonWriter.endObject();
        }

        @Override
        public T read(final JsonReader jsonReader) throws IOException, JsonParseException {
            JsonElement tree = Streams.parse(jsonReader);
            JsonObject object = tree.getAsJsonObject();

            String clazz = object.get("tipo").getAsString();
            JsonElement obj = object.get("obj").getAsJsonObject();

            if ("expressao".equals(clazz)) {
                return (T) gson.getDelegateAdapter(CustomRegraTypeAdapterFactory.this,
                        TypeToken.get(RegraExpressao.class)).fromJsonTree(obj);
            }

            if ("pontosPorRelato".equals(clazz)) {
                return (T) gson.getDelegateAdapter(CustomRegraTypeAdapterFactory.this,
                        TypeToken.get(RegraPontosPorRelato.class)).fromJsonTree(obj);
            }

            throw new JsonParseException("Erro ao desserializar " + type + ". No  uma regra?");
        }
    };
}