Example usage for com.google.gson.reflect TypeToken get

List of usage examples for com.google.gson.reflect TypeToken get

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken get.

Prototype

public static <T> TypeToken<T> get(Class<T> type) 

Source Link

Document

Gets type literal for the given Class instance.

Usage

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 .j a  v  a 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().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.");
    }//from  ww w .  j  av a  2  s .c om
    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.CollectionTypeAdapter.java

License:Open Source License

@Override
public void write(JsonWriter out, Collection<E> collection) throws IOException {
    if (collection == null) {
        out.nullValue();//from   w w  w  .  j av  a 2s  .c o  m
        return;
    }
    out.beginArray();
    for (E element : collection) {
        if (element != null && elementType != element.getClass()
                && (elementType instanceof TypeVariable<?> || elementType instanceof Class<?>)) {
            @SuppressWarnings("unchecked")
            TypeAdapter<E> runtimeTypeAdapter = (TypeAdapter<E>) gson
                    .getAdapter(TypeToken.get(element.getClass()));
            runtimeTypeAdapter.write(out, element);
        } else {
            elementTypeAdapter.write(out, element);
        }
    }
    out.endArray();
}

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

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (!Collection.class.isAssignableFrom(typeToken.getRawType()))
        return null;

    Type[] elementTypes = TypeUtils.getElementTypes(typeToken, Collection.class);
    if (elementTypes.length != 1)
        return null;
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementTypes[0]));
    Supplier<Collection<Object>> constructor = getConstructor(
            (Class<Collection<Object>>) typeToken.getRawType());
    return new Adapter(gson, elementTypes[0], elementTypeAdapter, constructor);
}

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

License:Open Source License

/**
 * Convert the json input into the result object corresponding to the call made
 * by id./*  www . j  a  v a 2  s.  c  om*/
 *
 * If the id is not known until after parsing, call
 * {@link #parseResult(Object, String)} on the return value of this call for a
 * second chance conversion.
 *
 * @param in
 *            json input 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 a JsonElement representing the result
 */
protected Object parseResult(JsonReader in, String id) throws JsonIOException, JsonSyntaxException {
    Type type = null;
    MethodProvider methodProvider = handler.getMethodProvider();
    if (methodProvider != null && id != 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));
                    try {
                        if (typeAdapter != null)
                            return typeAdapter.read(in);
                    } catch (IOException exception) {
                        throw new JsonIOException(exception);
                    }
                }
            }
        }
    }
    return fromJson(in, type);
}

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  w w. j  ava 2s  . c  o  m*/
 *            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.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != Multiset.class || !(type instanceof ParameterizedType)) {
        return null;
    }/* ww w .  j av a2 s  .c  o m*/

    Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
    TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
    return (TypeAdapter<T>) newMultisetAdapter(elementAdapter);
}

From source file:org.fs.net.converter.GsonConverterFactory.java

License:Apache License

private TypeAdapter<?> typeAdapterFromType(Type type) {
    return gson.getAdapter(TypeToken.get(type));
}

From source file:org.immutables.fixture.marshal.Marshaling.java

License:Apache License

@SuppressWarnings({ "resource", "unchecked" })
public static String toJson(Object object) {
    TypeAdapter<Object> adapter = GSON.getAdapter((TypeToken<Object>) TypeToken.get(object.getClass()));
    try {/*from  www.  j a  v  a 2s . co m*/
        StringWriter stringWriter = new StringWriter();
        JsonGeneratorWriter writer = new JsonGeneratorWriter(JSON_FACTORY.createGenerator(stringWriter));
        if (adapter instanceof com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.Adapter) {
            throw new IllegalStateException("Immutable adapters not registered");
        }
        GSON.toJson(object, object.getClass(), writer);
        writer.close();
        return stringWriter.toString();
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}

From source file:org.immutables.fixture.marshal.Marshaling.java

License:Apache License

@SuppressWarnings({ "resource", "unchecked" })
public static <T> T fromJson(String string, Class<T> type) {
    TypeAdapter<Object> adapter = GSON.getAdapter((TypeToken<Object>) TypeToken.get(type));
    try {/* www . j  a v a2  s  . co m*/
        if (adapter instanceof com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.Adapter) {
            throw new IllegalStateException("Immutable adapters not registered");
        }
        JsonParserReader reader = new JsonParserReader(JSON_FACTORY.createParser(string));
        return GSON.fromJson(reader, type);
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}