Java Code Examples for com.google.gson.TypeAdapter#fromJsonTree()

The following examples show how to use com.google.gson.TypeAdapter#fromJsonTree() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Convert the JsonElement into the result object corresponding to the call made
 * by id. If the result is already converted, does nothing.
 *
 * @param result
 *            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;
}
 
Example 2
Source File: GsonInterfaceAdapter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private <S> S readValue(JsonObject jsonObject, TypeToken<S> defaultTypeToken) throws IOException {
  try {
    TypeToken<S> actualTypeToken;
    if (jsonObject.isJsonNull()) {
      return null;
    } else if (jsonObject.has(OBJECT_TYPE)) {
      String className = jsonObject.get(OBJECT_TYPE).getAsString();
      Class<S> klazz = (Class<S>) Class.forName(className);
      actualTypeToken = TypeToken.get(klazz);
    } else if (defaultTypeToken != null) {
      actualTypeToken = defaultTypeToken;
    } else {
      throw new IOException("Could not determine TypeToken.");
    }
    TypeAdapter<S> delegate = this.gson.getDelegateAdapter(this.factory, actualTypeToken);
    S value = delegate.fromJsonTree(jsonObject.get(OBJECT_DATA));
    return value;
  } catch (ClassNotFoundException cnfe) {
    throw new IOException(cnfe);
  }
}
 
Example 3
Source File: OptionalTypeAdapterFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
    return new TypeAdapter<Optional<A>>() {
        @Override
        public Optional<A> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return Optional.empty();
            }
            else {
                JsonElement json = TypeAdapters.JSON_ELEMENT.read(in);
                try {
                    A value = innerAdapter.fromJsonTree(json);
                    return Optional.of(value);
                }
                catch (JsonSyntaxException e) {
                    /**
                     * Note : This is a workaround and it only exists because salt doesn't differentiate between a
                     * non-existent grain and a grain which exists but has value set to empty String.
                     *
                     * If an object is expected but instead empty string comes in then we return empty Optional.
                     */
                    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() &&
                            json.getAsString().isEmpty()) {
                        return Optional.empty();
                    }
                    throw e;
                }
            }
        }

        @Override
        public void write(JsonWriter out, Optional<A> optional) throws IOException {
            innerAdapter.write(out, optional.orElse(null));
        }
    };
}
 
Example 4
Source File: DataTypeAdapterFactory.java    From mvvm-starter with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create (Gson gson, TypeToken<T> type)
{
    final TypeAdapter<T>           lDelegate       = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> lElementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>()
    {
        @Override
        public void write (JsonWriter out, T value) throws IOException
        {
            lDelegate.write(out, value);
        }

        @Override
        public T read (JsonReader in) throws IOException
        {
            JsonElement lElement = lElementAdapter.read(in);
            if (lElement.isJsonObject())
            {
                JsonObject lObject = lElement.getAsJsonObject();
                if (lObject.has("data"))
                {
                    lElement = lObject.get("data");
                }
            }
            return lDelegate.fromJsonTree(lElement);
        }
    };
}
 
Example 5
Source File: OptionalTypeAdapterFactory.java    From salt-netapi-client with MIT License 5 votes vote down vote up
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
    return new TypeAdapter<Optional<A>>() {
        @Override
        public Optional<A> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return Optional.empty();
            } else {
                JsonElement json = TypeAdapters.JSON_ELEMENT.read(in);
                try {
                    A value = innerAdapter.fromJsonTree(json);
                    return Optional.of(value);
                }
                catch (JsonSyntaxException e) {
                    /**
                     * Note : This is a workaround and it only exists because salt doesn't differentiate between a
                     * non-existent grain and a grain which exists but has value set to empty String.
                     *
                     * If an object is expected but instead empty string comes in then we return empty Optional.
                     */
                    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() &&
                            json.getAsString().isEmpty()) {
                        return Optional.empty();
                    }
                    throw e;
                }
            }
        }

        @Override
        public void write(JsonWriter out, Optional<A> optional) throws IOException {
            innerAdapter.write(out, optional.orElse(null));
        }
    };
}
 
Example 6
Source File: CustomTypeAdapterFactory.java    From yawp with MIT License 4 votes vote down vote up
/**
 * Override this to define how this is deserialized in {@code deserialize} to
 * its type.
 */
protected T read(JsonReader in, TypeAdapter<JsonElement> elementAdapter, TypeAdapter<T> delegate) throws IOException {
    JsonElement tree = elementAdapter.read(in);
    afterRead(tree);
    return delegate.fromJsonTree(tree);
}
 
Example 7
Source File: SchemaParser.java    From qemu-java with GNU General Public License v2.0 4 votes vote down vote up
@Nonnull
public SchemaModel parse() throws IOException {
    SchemaModel model = new SchemaModel();

    Queue<URL> files = new LinkedList<URL>();
    files.add(this.file);

    while (!files.isEmpty()) {
        State state = new State(files.remove());

        for (;;) {
            // state.schemaReader.clearDocs();
            JsonToken token = state.jsonReader.peek();
            // LOG.info("Token is " + token);
            if (token == JsonToken.END_DOCUMENT)
                break;

            JsonObject jsonTree = parser.parse(state.jsonReader).getAsJsonObject();
            // LOG.info("Read generic " + jsonTree);

            // if (jsonTree.get("gen") != null) continue;

            Class<?> type;
            if (jsonTree.get("command") != null)
                type = QApiCommandDescriptor.class;
            else if (jsonTree.get("struct") != null)
                type = QApiStructDescriptor.class;
            else if (jsonTree.get("type") != null) {
                // 'struct' replaces 'type' after QEmu commit 895a2a8.
                jsonTree.add("struct", jsonTree.remove("type"));
                type = QApiTypeDescriptor.class;
            } else if (jsonTree.get("enum") != null)
                type = QApiEnumDescriptor.class;
            else if (jsonTree.get("union") != null)
                type = QApiUnionDescriptor.class;
            else if (jsonTree.get("alternate") != null)
                type = QApiAnonymousUnionDescriptor.class;
            else if (jsonTree.get("event") != null)
                type = QApiEventDescriptor.class;
            else if (jsonTree.get("include") != null)
                type = QApiIncludeDescriptor.class;
            else if (jsonTree.get("pragma") != null)
                continue; // ignore pragma sections
            else
                throw new IllegalArgumentException("Unknown JsonObject " + jsonTree);
            // LOG.info("Tree is " + jsonTree + "; docs are " + state.schemaReader.getDocs());

            TypeAdapter<?> adapter = gson.getAdapter(type);
            Object object;
            try {
                object = adapter.fromJsonTree(jsonTree);
            } catch (JsonSyntaxException e) {
                throw new JsonSyntaxException("Failed to parse " + jsonTree, e);
            }
            if (object instanceof QApiIncludeDescriptor) {
                files.add(new URL(state.file, ((QApiIncludeDescriptor) object).include));
                continue;
            }

            QApiElementDescriptor element = (QApiElementDescriptor) object;
            // element.docs = state.schemaReader.getDocs();
            element.setModel(model);
            model.elements.put(element.getName(), element);

            if ((element instanceof AbstractQApiTypeDescriptor) && (((AbstractQApiTypeDescriptor) element).base instanceof Map)) {
                QApiTypeDescriptor parentElement = QApiTypeDescriptor.fromMap(
                        (Map) ((AbstractQApiTypeDescriptor) element).base,
                        element.getName() + "Base");
                model.elements.put(parentElement.getName(), parentElement);
            }
            // LOG.info("Read specific " + element);
        }

        state.jsonReader.close();
    }

    return model;
}