com.google.gson.TypeAdapter Java Examples

The following examples show how to use com.google.gson.TypeAdapter. 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: MessagesModule.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
@Override
protected void configure() {
   Multibinder<TypeAdapterFactory> typeAdapterFactoryBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<TypeAdapterFactory>() {});
   typeAdapterFactoryBinder.addBinding().to(AddressTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(GsonReferenceTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(MessageTypeAdapterFactory.class);
   typeAdapterFactoryBinder.addBinding().to(MessageBodyTypeAdapterFactory.class);

   Multibinder<TypeAdapter<?>> typeAdapterBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<TypeAdapter<?>>() {});
   typeAdapterBinder.addBinding().to(ProtocolDeviceIdTypeAdapter.class);
   typeAdapterBinder.addBinding().to(HubMessageTypeAdapter.class);

   Multibinder<JsonSerializer<?>> serializerBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<JsonSerializer<?>>() {});
   serializerBinder.addBinding().to(ClientMessageTypeAdapter.class);
   serializerBinder.addBinding().to(ResultTypeAdapter.class);

   Multibinder<JsonDeserializer<?>> deserializerBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<JsonDeserializer<?>>() {});
   deserializerBinder.addBinding().to(ClientMessageTypeAdapter.class);
   deserializerBinder.addBinding().to(ResultTypeAdapter.class);
}
 
Example #2
Source File: DateOnlyTypeAdapterFactory.java    From plaid-java with MIT License 6 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  if (!Date.class.isAssignableFrom(type.getRawType())) {
    return null;
  }

  return new TypeAdapter<T>() {
    @Override
    public void write(JsonWriter out, T value) throws IOException {
      // date formatters not thread safe :'(
      synchronized (simpleDateFormat) {
        out.value(simpleDateFormat.format((Date) value));
      }
    }

    @Override
    public T read(JsonReader in) throws IOException {
      throw new UnsupportedOperationException("read() is not implemented");
    }
  };
}
 
Example #3
Source File: CollectionTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out, Collection<E> collection) throws IOException {
	if (collection == null) {
		out.nullValue();
		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();
}
 
Example #4
Source File: UpgradePathTransformationRequest.java    From butterfly with MIT License 6 votes vote down vote up
private String toJson() {
    if (gson == null) {
        gson = new GsonBuilder().serializeNulls().setPrettyPrinting().registerTypeAdapter(File.class, new TypeAdapter<File>() {
            @Override
            public void write(JsonWriter jsonWriter, File file) throws IOException {
                String fileAbsolutePath = (file == null ? null : file.getAbsolutePath());
                jsonWriter.value(fileAbsolutePath);
            }
            @Override
            public File read(JsonReader jsonReader) {
                throw new UnsupportedOperationException("There is no support for deserializing UpgradePathTransformationRequest objects at the moment");
            }
        }).create();
    }
    return gson.toJson(this);
}
 
Example #5
Source File: TransformationResultImpl.java    From butterfly with MIT License 6 votes vote down vote up
@Override
public String toJson() {
    if (gson == null) {
        gson = new GsonBuilder().serializeNulls().setPrettyPrinting().registerTypeAdapter(File.class, new TypeAdapter<File>() {
            @Override
            public void write(JsonWriter jsonWriter, File file) throws IOException {
                String fileAbsolutePath = (file == null ? null : file.getAbsolutePath());
                jsonWriter.value(fileAbsolutePath);
            }
            @Override
            public File read(JsonReader jsonReader) {
                throw new UnsupportedOperationException("There is no support for deserializing transformation result objects at the moment");
            }
        }).create();
    }
    return gson.toJson(this);
}
 
Example #6
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 #7
Source File: ProteusTypeAdapterFactory.java    From proteus with Apache License 2.0 6 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  Class clazz = type.getRawType();

  if (clazz == Primitive.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) PRIMITIVE_TYPE_ADAPTER;
  } else if (clazz == ObjectValue.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) OBJECT_TYPE_ADAPTER;
  } else if (clazz == Array.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) ARRAY_TYPE_ADAPTER;
  } else if (clazz == Null.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) NULL_TYPE_ADAPTER;
  } else if (clazz == Layout.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) LAYOUT_TYPE_ADAPTER;
  } else if (clazz == Value.class) {
    //noinspection unchecked
    return (TypeAdapter<T>) VALUE_TYPE_ADAPTER;
  }

  return null;
}
 
Example #8
Source File: TypeAdapters.java    From immutables with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  if (ID_TYPE_TOKEN.equals(type)) {
    return (TypeAdapter<T>) WRAPPED_ID_ADAPTER;
  }
  if (TIME_INSTANT_TYPE_TOKEN.equals(type)) {
    return (TypeAdapter<T>) WRAPPED_TIME_INSTANT_ADAPTER;
  }
  if (BINARY_TYPE_TOKEN.equals(type)) {
    return (TypeAdapter<T>) WRAPPED_BINARY_ADAPTER;
  }
  if (PATTERN_TYPE_TOKEN.equals(type)) {
    return (TypeAdapter<T>) PATTERN_ADAPTER;
  }
  if (DECIMAL128_TYPE_TOKEN.equals(type)) {
    return (TypeAdapter<T>) DECIMAL128_ADAPTER;
  }
  return null;
}
 
Example #9
Source File: XorTypeAdapterFactory.java    From salt-netapi-client with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <A> TypeAdapter<A> create(Gson gson, TypeToken<A> typeToken) {
    Type type = typeToken.getType();
    boolean isXor = typeToken.getRawType() == Xor.class;
    boolean isParameterized = type instanceof ParameterizedType;
    boolean isSSHResult = ResultSSHResultTypeAdapterFactory.isResultSSHResult(type);
    if (isXor && isParameterized && !isSSHResult) {
        Type leftType = ((ParameterizedType) type).getActualTypeArguments()[0];
        Type rightType = ((ParameterizedType) type).getActualTypeArguments()[1];
        TypeAdapter<?> rightAdapter = gson.getAdapter(TypeToken.get(rightType));
        if (leftType.equals(SaltError.class)) {
            return (TypeAdapter<A>) errorAdapter(rightAdapter);
        }

        TypeAdapter<?> leftAdapter = gson.getAdapter(TypeToken.get(leftType));
        return (TypeAdapter<A>) xorAdapter(leftAdapter, rightAdapter);
    } else {
        return null;
    }
}
 
Example #10
Source File: AutoValueTypeAdapterFactory.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<? super T> rawType = type.getRawType();

    // Only deserialize classes decorated with @AutoGson.
    AutoGson annotation = rawType.getAnnotation(AutoGson.class);
    if (annotation != null) {
        return (TypeAdapter<T>) gson.getAdapter(annotation.autoValueClass()).nullSafe();
    } else if (rawType.equals(SlicingProgressEntity.class)) {
        return (TypeAdapter<T>) SlicingProgressEntity.typeAdapter(gson).nullSafe();
    } else if (rawType.equals(SlicingProgress.class)) {
        return (TypeAdapter<T>) SlicingProgress.typeAdapter(gson).nullSafe();
    }
    return null;
}
 
Example #11
Source File: TypeAdapters.java    From letv with Apache License 2.0 6 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (typeToken.getRawType() != Timestamp.class) {
        return null;
    }
    final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
    return new TypeAdapter<Timestamp>() {
        public Timestamp read(JsonReader in) throws IOException {
            Date date = (Date) dateTypeAdapter.read(in);
            return date != null ? new Timestamp(date.getTime()) : null;
        }

        public void write(JsonWriter out, Timestamp value) throws IOException {
            dateTypeAdapter.write(out, value);
        }
    };
}
 
Example #12
Source File: SerdeUtils.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to serialize Java objects as json strings
 * @param name name of object used for logging
 * @param object object to be serialized
 * @return Json representation of the object
 */
public static String toJson(String name, Object object) {
  final Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC)
      // Tells Gson how to serialize fields with type of Class.
      .registerTypeHierarchyAdapter(Class.class, new TypeAdapter<Class>() {
        @Override
        public void write(JsonWriter out, Class value) throws IOException {
          if (value == null) {
            out.nullValue();
          } else {
            out.value(value.getName());
          }
        }

        @Override
        public Class read(JsonReader in) {
          throw new SamzaException("Deserialization from json is not supported.");
        }
      }).create();
  try {
    return gson.toJson(object);
  } catch (Exception e) {
    throw new SamzaException(String.format("Failed to serialize %s to json", name), e);
  }
}
 
Example #13
Source File: ArrayAdapterFactory.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

    TypeAdapter<T> typeAdapter = null;

    try {
        if (type.getRawType() == List.class)
            typeAdapter = new ArrayAdapter(
                    (Class) ((ParameterizedType) type.getType())
                            .getActualTypeArguments()[0]);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return typeAdapter;


}
 
Example #14
Source File: CollectionTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
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;
	Type elementType = elementTypes[0];
	TypeAdapter<?> elementTypeAdapter;
	if (elementType == Object.class)
		elementTypeAdapter = new JsonElementTypeAdapter(gson);
	else
		elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
	Supplier<Collection<Object>> constructor = getConstructor((Class<Collection<Object>>) typeToken.getRawType());
	return (TypeAdapter<T>) create(gson, elementType, elementTypeAdapter, constructor);
}
 
Example #15
Source File: IrisObjectTypeAdapter.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }

  TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
  if (typeAdapter instanceof IrisObjectTypeAdapter) {
    out.beginObject();
    out.endObject();
    return;
  }

  typeAdapter.write(out, value);
}
 
Example #16
Source File: LowercaseEnumTypeAdapterFactory.java    From messenger4j with MIT License 5 votes vote down vote up
/**
 * Transforms the given enum constant to lower case. If a {@code SerializedName} annotation is
 * present, the default adapter result is returned.
 *
 * @param enumConstant the enumeration constant
 * @param delegateAdapter the default adapter of the given type
 * @return the transformed string representation of the constant
 */
private <T> String transform(T enumConstant, TypeAdapter<T> delegateAdapter) {
  try {
    final String enumValue = ((Enum) enumConstant).name();
    final boolean hasSerializedNameAnnotation =
        enumConstant.getClass().getField(enumValue).isAnnotationPresent(SerializedName.class);
    return hasSerializedNameAnnotation
        ? delegateAdapter.toJsonTree(enumConstant).getAsString()
        : enumValue.toLowerCase();
  } catch (NoSuchFieldException e) {
    // should never happen
    throw new RuntimeException(e);
  }
}
 
Example #17
Source File: ReflectiveTypeAdapterFactory.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
private TypeAdapter<?> getFieldAdapter(Gson gson, Field field, TypeToken<?> fieldType) {
  JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);
  if (annotation != null) {
    TypeAdapter<?> adapter = getTypeAdapter(constructorConstructor, gson, fieldType, annotation);
    if (adapter != null) return adapter;
  }
  return gson.getAdapter(fieldType);
}
 
Example #18
Source File: Iso8601DateTypeAdapter.java    From cnode-android with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    return type.getRawType() == Date.class
            ? (TypeAdapter<T>) new Iso8601DateTypeAdapter()
            : null;
}
 
Example #19
Source File: DBFluteGsonAdaptable.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<? super T> rawType = type.getRawType();
    if (rawType != null && LaClassificationUtil.isCls(rawType)) {
        @SuppressWarnings("unchecked")
        final TypeAdapter<T> pter = (TypeAdapter<T>) createTypeAdapterClassification(rawType);
        return pter;
    } else {
        return null;
    }
}
 
Example #20
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactoryForMultipleTypes(final Class<TT> base, final Class<? extends TT> sub, final TypeAdapter<? super TT> typeAdapter) {
    return new TypeAdapterFactory() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            return (rawType == base || rawType == sub) ? typeAdapter : null;
        }

        public String toString() {
            return "Factory[type=" + base.getName() + "+" + sub.getName() + ",adapter=" + typeAdapter + "]";
        }
    };
}
 
Example #21
Source File: DocumentSymbolResponseAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
	PropertyChecker leftChecker = new PropertyChecker("location");
	PropertyChecker rightChecker = new PropertyChecker("range");
	TypeAdapter<Either<SymbolInformation, DocumentSymbol>> elementTypeAdapter = new EitherTypeAdapter<>(gson,
			ELEMENT_TYPE, leftChecker, rightChecker);
	return (TypeAdapter<T>) new CollectionTypeAdapter<>(gson, ELEMENT_TYPE.getType(), elementTypeAdapter, ArrayList::new);
}
 
Example #22
Source File: c.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public TypeAdapter create(Gson gson, TypeToken typetoken)
{
    if (typetoken.getRawType() == java/util/Date)
    {
        return new DateTypeAdapter();
    } else
    {
        return null;
    }
}
 
Example #23
Source File: ActionTypeAdapter.java    From graphical-lsp with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
	if (!Action.class.isAssignableFrom(typeToken.getRawType()))
		return null;
	return (TypeAdapter<T>) new ActionTypeAdapter(gson, actions);
}
 
Example #24
Source File: GsonRequest.java    From jus with Apache License 2.0 5 votes vote down vote up
public <R> GsonRequest<T> setRequestData(R requestData, Gson gson) {
    TypeAdapter<?> adapter;
    if(requestData==null) {
        adapter = gson.getAdapter(Object.class);
    } else {
         adapter = gson.getAdapter(TypeToken.get(requestData.getClass()));
    }
    return setRequestData(requestData, gson, adapter);
}
 
Example #25
Source File: GsonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Gson Factory which gives preference to existing adapters from {@code gson} instance. However,
 * if type is not supported it will query {@link CodecRegistry} to create one (if possible).
 *
 * <p>This allows supporting Bson types by Gson natively (eg. for {@link org.bson.types.ObjectId}).
 *
 * @param registry existing registry which will be used if type is unknown to {@code gson}.
 * @return factory which delegates to {@code registry} for unknown types.
 */
public static TypeAdapterFactory delegatingTypeAdapterFactory(final CodecRegistry registry) {
  Preconditions.checkNotNull(registry, "registry");
  return new TypeAdapterFactory() {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      boolean hasAdapter;
      try {
        TypeAdapter<T> adapter = gson.getDelegateAdapter(this, type);
        hasAdapter = !isReflectiveTypeAdapter(adapter);
      } catch (IllegalArgumentException e) {
        hasAdapter = false;
      }

      if (hasAdapter) {
        return null;
      }

      try {
        @SuppressWarnings("unchecked")
        Codec<T> codec = (Codec<T>) registry.get(type.getRawType());
        return typeAdapterFromCodec(codec);
      } catch (CodecConfigurationException e1) {
        return null;
      }

    }
  };
}
 
Example #26
Source File: TypeAdapters.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactory(
    final Class<TT> unboxed, final Class<TT> boxed, final TypeAdapter<? super TT> typeAdapter) {
  return new TypeAdapterFactory() {
    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
      Class<? super T> rawType = typeToken.getRawType();
      return (rawType == unboxed || rawType == boxed) ? (TypeAdapter<T>) typeAdapter : null;
    }
    @Override public String toString() {
      return "Factory[type=" + boxed.getName()
          + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]";
    }
  };
}
 
Example #27
Source File: TypeAdapterRuntimeTypeWrapper.java    From gson with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, T value) throws IOException {
  // Order of preference for choosing type adapters
  // First preference: a type adapter registered for the runtime type
  // Second preference: a type adapter registered for the declared type
  // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
  // Fourth preference: reflective type adapter for the declared type

  TypeAdapter chosen = delegate;
  Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);
  if (runtimeType != type) {
    TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));
    if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
      // The user registered a type adapter for the runtime type, so we will use that
      chosen = runtimeTypeAdapter;
    } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {
      // The user registered a type adapter for Base class, so we prefer it over the
      // reflective type adapter for the runtime type
      chosen = delegate;
    } else {
      // Use the type adapter for runtime type
      chosen = runtimeTypeAdapter;
    }
  }
  chosen.write(out, value);
}
 
Example #28
Source File: GsonEosTypeAdapterFactory.java    From EosCommander with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    TypeAdapter<T> typeAdapter = null;
    Class<?> currentType = Object.class;
    for (Class<?> type : adapters.keySet()) {
        if (type.isAssignableFrom(typeToken.getRawType())) {
            if (currentType.isAssignableFrom(type)) {
                currentType = type;
                typeAdapter = (TypeAdapter<T>)adapters.get(type);
            }
        }
    }
    return typeAdapter;
}
 
Example #29
Source File: JsonAdapterAnnotationOnFieldsTest.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
  return new TypeAdapter<T>() {
    @Override public void write(JsonWriter out, T value) throws IOException {
      out.value("GizmoPartTypeAdapterFactory");
    }
    @SuppressWarnings("unchecked")
    @Override public T read(JsonReader in) throws IOException {
      in.nextString();
      return (T) Arrays.asList(new Part("GizmoPartTypeAdapterFactory"));
    }
  };
}
 
Example #30
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));
        }
    };
}