Example usage for com.google.gson TypeAdapter fromJsonTree

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

Introduction

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

Prototype

public final T fromJsonTree(JsonElement jsonTree) 

Source Link

Document

Converts jsonTree to a Java object.

Usage

From source file:networkUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//  w  w w.  ja v a2s . 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);
            String label = predicate.process(jsonElement);
            @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 { // Unimplemented as we don't use write.
            /*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(null, out);
        }
    };
}

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;
    }/*from  w ww  .  j a v a  2s  .  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);
            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;
    }/*ww  w .  ja v a 2s .  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:org.eclipse.lsp4j.jsonrpc.debug.adapters.DebugMessageTypeAdapter.java

License:Open Source License

private Message createMessage(String messageType, int seq, int request_seq, String method, boolean success,
        String errorMessage, Object params, Object body) throws JsonParseException {
    if (messageType == null) {
        throw new JsonParseException("Unable to identify the input message. Missing 'type' field.");
    }/*  ww w  . ja  va  2 s . co m*/
    switch (messageType) {
    case "request": {
        DebugRequestMessage message = new DebugRequestMessage();
        message.setId(seq);
        message.setMethod(method);
        message.setParams(params);
        return message;
    }
    case "event": {
        DebugNotificationMessage message = new DebugNotificationMessage();
        message.setId(seq);
        message.setMethod(method);
        message.setParams(body);
        return message;
    }
    case "response": {
        DebugResponseMessage message = new DebugResponseMessage();
        message.setId(request_seq);
        message.setResponseId(seq);
        message.setMethod(method);
        if (!success) {
            ResponseError error = new ResponseError();
            error.setCode(ResponseErrorCode.UnknownErrorCode);
            error.setData(body);
            if (errorMessage == null) {
                // Some debug servers/clients don't provide a "message" field on an error.
                // Generally in those cases the body has some extra details to figure out
                // what went wrong.
                errorMessage = "Unset error message.";
            }
            error.setMessage(errorMessage);
            message.setError(error);
        } else {
            if (body instanceof JsonElement) {
                // Type of result could not be resolved - try again with the parsed JSON tree
                MethodProvider methodProvider = handler.getMethodProvider();
                if (methodProvider != null) {
                    String resolvedMethod = methodProvider.resolveMethod(Integer.toString(request_seq));
                    if (resolvedMethod != null) {
                        JsonRpcMethod jsonRpcMethod = handler.getJsonRpcMethod(resolvedMethod);
                        if (jsonRpcMethod != null) {
                            TypeAdapter<?> typeAdapter = null;
                            Type returnType = jsonRpcMethod.getReturnType();
                            if (jsonRpcMethod.getReturnTypeAdapterFactory() != null)
                                typeAdapter = jsonRpcMethod.getReturnTypeAdapterFactory().create(gson,
                                        TypeToken.get(returnType));
                            JsonElement jsonElement = (JsonElement) body;
                            if (typeAdapter != null)
                                body = typeAdapter.fromJsonTree(jsonElement);
                            else
                                body = gson.fromJson(jsonElement, returnType);
                        }
                    }
                }
            }
            message.setResult(body);
        }
        return message;
    }
    default:
        throw new JsonParseException("Unable to identify the input message.");
    }
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapter.java

License:Open Source License

/**
 * Convert the JsonElement into the result object corresponding to the call made
 * by id. If the result is already converted, does nothing.
 *
 * @param result/*  w  ww  . j a  v  a 2 s .  c om*/
 *            json element to read from
 * @param id
 *            id of request message this is in response to
 * @return correctly typed object if the correct expected type can be
 *         determined, or result unmodified if no conversion can be done.
 */
protected Object parseResult(Object result, String id) throws JsonSyntaxException {
    if (result instanceof JsonElement) {
        // Type of result could not be resolved - try again with the parsed JSON tree
        Type type = null;
        MethodProvider methodProvider = handler.getMethodProvider();
        if (methodProvider != null) {
            String resolvedMethod = methodProvider.resolveMethod(id);
            if (resolvedMethod != null) {
                JsonRpcMethod jsonRpcMethod = handler.getJsonRpcMethod(resolvedMethod);
                if (jsonRpcMethod != null) {
                    type = jsonRpcMethod.getReturnType();
                    if (jsonRpcMethod.getReturnTypeAdapterFactory() != null) {
                        TypeAdapter<?> typeAdapter = jsonRpcMethod.getReturnTypeAdapterFactory().create(gson,
                                TypeToken.get(type));
                        if (typeAdapter != null)
                            return typeAdapter.fromJsonTree((JsonElement) result);
                    }
                }
            }
        }
        return fromJson((JsonElement) result, type);
    }
    return result;
}

From source file:org.lanternpowered.server.script.json.ObjectTypeAdapterFactory.java

License:MIT License

protected V deserialize(TypeToken<V> type, JsonElement element, Gson gson) {
    final JsonObject obj = element.getAsJsonObject();
    final String valueTypeId = obj.get(TYPE).getAsString();
    //noinspection unchecked
    final Optional<O> optType = this.registry.getById(valueTypeId);
    if (!optType.isPresent()) {
        throw new IllegalStateException("Unknown type id: " + valueTypeId);
    }// w  w  w.j  a v a2 s  .c  o  m
    //noinspection unchecked
    final TypeAdapter<V> delegateTypeAdapter = gson.getDelegateAdapter(this,
            (TypeToken<V>) TypeToken.get(optType.get().getType()));
    try {
        return delegateTypeAdapter.fromJsonTree(obj.get(DATA));
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to compile the " + this.typeToken.toString() + " from the json: " + obj.toString(), e);
    }
}

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  va  2  s . c  om*/

    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.mm.ModuleIndexParser.java

License:Apache License

public ModuleIndexParser(URL remoteUrl) throws IOException {

    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    TypeAdapter<ModuleInfo> adapter = gson.getAdapter(ModuleInfo.class);

    try (InputStreamReader reader = new InputStreamReader(remoteUrl.openStream(), Charset.forName("UTF-8"))) {

        // reading everything at once is possible with the following two lines
        // but we don't want the entire process to fail if individual modules
        // cannot be read.

        //  TypeToken<?> typeToken = new TypeToken<Map<String, ModuleInfo>>() { /* trick type erasure */ };
        //  Map<String, ModuleInfo> infos = new Gson().fromJson(reader, typeToken.getType());

        JsonElement tree = parser.parse(reader);

        if (!tree.isJsonObject()) {
            throw new IllegalStateException("Root element must be a map");
        }/*from w w w  .j  a va2  s. c o m*/

        JsonObject jsonObject = tree.getAsJsonObject();

        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            try {
                ModuleInfo info = adapter.fromJsonTree(entry.getValue());
                registerEntry(info);
            } catch (Exception e) {
                logger.warn("Encountered invalid entry \"{}\" - {}", entry.getKey(), e.getMessage());
            }
        }

    }
}

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;
    }//ww 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: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  va 2  s . c  om

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