com.google.gson.TypeAdapterFactory Java Examples

The following examples show how to use com.google.gson.TypeAdapterFactory. 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: RuleConfigJsonModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   bindSetOf(TypeAdapterFactory.class)
      .addBinding()
      .toInstance(createConditionConfigSerializer());
   bindSetOf(TypeAdapterFactory.class)
      .addBinding()
      .toInstance(createActionConfigSerializer());
   bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .to(AttributeTypeAdapter.class)
      .asEagerSingleton();
   bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .to(TemplatedExpressionTypeAdapter.class)
      .asEagerSingleton();
}
 
Example #2
Source File: RuleConfigJsonModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private TypeAdapterFactory createConditionConfigSerializer() {
   return
         RuntimeTypeAdapterFactory
            .of(ConditionConfig.class, ATT_TYPE)
            .registerSubtype(ContextQueryConfig.class, ContextQueryConfig.TYPE)
            .registerSubtype(DayOfWeekConfig.class, DayOfWeekConfig.TYPE)
            .registerSubtype(DurationConfig.class, DurationConfig.TYPE)
            .registerSubtype(OrConfig.class, OrConfig.TYPE)
            .registerSubtype(QueryChangeConfig.class, QueryChangeConfig.TYPE)
            .registerSubtype(IfConditionConfig.class, IfConditionConfig.TYPE)
            .registerSubtype(ReceivedMessageConfig.class, ReceivedMessageConfig.TYPE)
            .registerSubtype(ReferenceFilterConfig.class, ReferenceFilterConfig.TYPE)
            .registerSubtype(ThresholdConfig.class, ThresholdConfig.TYPE)
            .registerSubtype(TimeOfDayConfig.class, TimeOfDayConfig.TYPE)
            .registerSubtype(ValueChangeConfig.class, ValueChangeConfig.TYPE)
            ;
}
 
Example #3
Source File: GsonModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
   bind(com.iris.io.json.JsonSerializer.class).to(GsonSerializerImpl.class);
   bind(com.iris.io.json.JsonDeserializer.class).to(GsonDeserializerImpl.class);

   Multibinder
   	.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonSerializer<?>>() {})
   	.addBinding()
   	.to(AttributeMapSerializer.class);
   Multibinder
   	.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonDeserializer<?>>() {})
   	.addBinding()
   	.to(AttributeMapSerializer.class);
   Multibinder
      .newSetBinder(binder(), new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .to(ByteArrayToBase64TypeAdapter.class);
   Multibinder
      .newSetBinder(binder(), new TypeLiteral<TypeAdapterFactory>() {})
      .addBinding()
      .to(TypeTypeAdapterFactory.class);
}
 
Example #4
Source File: TypeAdapters.java    From letv with Apache License 2.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() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            return (rawType == unboxed || rawType == boxed) ? typeAdapter : null;
        }

        public String toString() {
            return "Factory[type=" + boxed.getName() + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]";
        }
    };
}
 
Example #5
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newTypeHierarchyFactory(final Class<TT> clazz, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return clazz.isAssignableFrom(typeToken.getRawType()) ? typeAdapter : null;
        }

        public String toString() {
            return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
        }
    };
}
 
Example #6
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactory(final Class<TT> type, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return typeToken.getRawType() == type ? typeAdapter : null;
        }

        public String toString() {
            return "Factory[type=" + type.getName() + ",adapter=" + typeAdapter + "]";
        }
    };
}
 
Example #7
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return typeToken.equals(type) ? typeAdapter : null;
        }
    };
}
 
Example #8
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
                return null;
            }
            if (!rawType.isEnum()) {
                rawType = rawType.getSuperclass();
            }
            return new EnumTypeAdapter(rawType);
        }
    };
}
 
Example #9
Source File: GsonFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers
) {
   this(typeAdapterFactories, typeAdapters, serializers, deserializers, true);
}
 
Example #10
Source File: RuleConfigJsonModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private TypeAdapterFactory createActionConfigSerializer() {
   return
      RuntimeTypeAdapterFactory
         .of(ActionConfig.class, ATT_TYPE)
         .registerSubtype(SendActionConfig.class, SendActionConfig.TYPE)
         .registerSubtype(SendNotificationActionConfig.class, SendNotificationActionConfig.TYPE)
         .registerSubtype(SetAttributeActionConfig.class, SetAttributeActionConfig.TYPE)
         .registerSubtype(ForEachModelActionConfig.class, ForEachModelActionConfig.TYPE)
         .registerSubtype(LogActionConfig.class, LogActionConfig.TYPE)
         .registerSubtype(ActionListConfig.class, ActionListConfig.TYPE);
}
 
Example #11
Source File: ActionConfigJsonModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
   bindSetOf(TypeAdapterFactory.class)
      .addBinding()
      .toInstance(createActionConfigSerializer());
   bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .toInstance(new AttributeTypeAdapter());
   bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
      .addBinding()
      .toInstance(new TemplatedExpressionTypeAdapter());
}
 
Example #12
Source File: RuntimeTypeAdapterFactoryTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testSerializeCollidingTypeFieldName() {
  TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv")
      .registerSubtype(CreditCard.class);
  Gson gson = new GsonBuilder()
      .registerTypeAdapterFactory(billingAdapter)
      .create();
  try {
    gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class);
    fail();
  } catch (JsonParseException expected) {
  }
}
 
Example #13
Source File: JsonAdapterAnnotationTypeAdapterFactory.java    From gson with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" }) // Casts guarded by conditionals.
TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
    TypeToken<?> type, JsonAdapter annotation) {
  Object instance = constructorConstructor.get(TypeToken.get(annotation.value())).construct();

  TypeAdapter<?> typeAdapter;
  if (instance instanceof TypeAdapter) {
    typeAdapter = (TypeAdapter<?>) instance;
  } else if (instance instanceof TypeAdapterFactory) {
    typeAdapter = ((TypeAdapterFactory) instance).create(gson, type);
  } else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) {
    JsonSerializer<?> serializer = instance instanceof JsonSerializer
        ? (JsonSerializer) instance
        : null;
    JsonDeserializer<?> deserializer = instance instanceof JsonDeserializer
        ? (JsonDeserializer) instance
        : null;
    typeAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null);
  } else {
    throw new IllegalArgumentException("Invalid attempt to bind an instance of "
        + instance.getClass().getName() + " as a @JsonAdapter for " + type.toString()
        + ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory,"
        + " JsonSerializer or JsonDeserializer.");
  }

  if (typeAdapter != null && annotation.nullSafe()) {
    typeAdapter = typeAdapter.nullSafe();
  }

  return typeAdapter;
}
 
Example #14
Source File: GsonModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Provides
public GsonFactory gson(
   Set<TypeAdapterFactory> typeAdapterFactories,
   Set<TypeAdapter<?>> typeAdapters,
   Set<JsonSerializer<?>> serializers,
   Set<JsonDeserializer<?>> deserializers
) {
   return new GsonFactory(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example #15
Source File: PolymorphicTypeAdapterFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public ReflectiveTypeAdapter(
      Gson gson, 
      TypeAdapterFactory skipPast, 
      TypeToken<T> token
) {
   this.gson = gson;
   this.token = token;
}
 
Example #16
Source File: GsonFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers,
      boolean serializeNulls
) {
   this.gson = create(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example #17
Source File: TypeAdapters.java    From gson with Apache License 2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactory(
    final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
  return new TypeAdapterFactory() {
    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
      return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
    }
  };
}
 
Example #18
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 #19
Source File: EnumTypeAdapter.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {
        @SuppressWarnings({"unchecked"})
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
                return null;
            }
            if (!rawType.isEnum()) {
                rawType = rawType.getSuperclass(); // handle anonymous subclasses
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
 
Example #20
Source File: JsonRpcMethod.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
private JsonRpcMethod(String methodName, Type[] parameterTypes, Type returnType, TypeAdapterFactory returnTypeAdapterFactory,
		boolean isNotification) {
	if (methodName == null)
		throw new NullPointerException("methodName");
	this.methodName = methodName;
	this.parameterTypes = parameterTypes;
	this.returnType = returnType;
	this.returnTypeAdapterFactory = returnTypeAdapterFactory;
	this.isNotification = isNotification;
}
 
Example #21
Source File: TreeTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
    Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
  this.serializer = serializer;
  this.deserializer = deserializer;
  this.gson = gson;
  this.typeToken = typeToken;
  this.skipPast = skipPast;
}
 
Example #22
Source File: DataConverterImpl.java    From yandex-translate-api with MIT License 5 votes vote down vote up
private static Gson createConverter() {
    final GsonBuilder builder = new GsonBuilder();
    final ServiceLoader<TypeAdapterFactory> serviceLoader =
        ServiceLoader.load(TypeAdapterFactory.class);

    serviceLoader.forEach(builder::registerTypeAdapterFactory);

    return builder.create();
}
 
Example #23
Source File: GsonAutoValueSpeakerTest.java    From Jolyglot with Apache License 2.0 5 votes vote down vote up
@Override protected Jolyglot jolyglot() {
  return new GsonAutoValueSpeaker() {
    @Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
      return new TypeAdapterFactory() {
        @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
          return gson.getDelegateAdapter(this, type);
        }
      };
    }
  };
}
 
Example #24
Source File: CategoriesTypeAdapter.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
	return new TypeAdapterFactory() {

		@SuppressWarnings("unchecked")
		@Override
		public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
			if (Categories.class.isAssignableFrom(type.getRawType())) {
				return (TypeAdapter<T>) new CategoriesTypeAdapter(gson, encryptorProviderService);
			}
			return null;
		}
	};
}
 
Example #25
Source File: TransactionsTypeAdapter.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
	return new TypeAdapterFactory() {

		@SuppressWarnings("unchecked")
		@Override
		public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
			if (Transactions.class.isAssignableFrom(type.getRawType())) {
				return (TypeAdapter<T>) new TransactionsTypeAdapter(gson, encryptorProviderService);
			}
			return null;
		}
	};
}
 
Example #26
Source File: GeometryAdapterFactory.java    From mapbox-java with MIT License 5 votes vote down vote up
/**
 * Create a new instance of Geometry type adapter factory, this is passed into the Gson
 * Builder.
 *
 * @return a new GSON TypeAdapterFactory
 * @since 4.4.0
 */
public static TypeAdapterFactory create() {

  if (geometryTypeFactory == null) {
    geometryTypeFactory = RuntimeTypeAdapterFactory.of(Geometry.class, "type", true)
      .registerSubtype(GeometryCollection.class, "GeometryCollection")
      .registerSubtype(Point.class, "Point")
      .registerSubtype(MultiPoint.class, "MultiPoint")
      .registerSubtype(LineString.class, "LineString")
      .registerSubtype(MultiLineString.class, "MultiLineString")
      .registerSubtype(Polygon.class, "Polygon")
       .registerSubtype(MultiPolygon.class, "MultiPolygon");
  }
  return geometryTypeFactory;
}
 
Example #27
Source File: GsonAutoValueSpeakerGenericsTest.java    From Jolyglot with Apache License 2.0 5 votes vote down vote up
@Override protected JolyglotGenerics jolyglot() {
  return new GsonAutoValueSpeaker() {
    @Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
      return new TypeAdapterFactory() {
        @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
          return gson.getDelegateAdapter(this, type);
        }
      };
    }
  };
}
 
Example #28
Source File: GsonValueMapperFactory.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private TypeAdapterFactory adapterFor(Class superClass, List<Class<?>> implementations, TypeInfoGenerator infoGen, MessageBundle messageBundle) {
    RuntimeTypeAdapterFactory adapterFactory = RuntimeTypeAdapterFactory.of(superClass, ValueMapper.TYPE_METADATA_FIELD_NAME);
    if (implementations.isEmpty()) {
        return null;
    }
    implementations.stream()
            .filter(impl -> !ClassUtils.isAbstract(impl))
            .forEach(impl -> adapterFactory.registerSubtype(impl, infoGen.generateTypeName(GenericTypeReflector.annotate(impl), messageBundle)));

    return adapterFactory;
}
 
Example #29
Source File: NetworkModule.java    From octoandroid with GNU General Public License v3.0 5 votes vote down vote up
@Provides
    @Singleton
    Gson provideGson(TypeAdapterFactory typeAdapterFactory) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapterFactory(typeAdapterFactory);
//        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }
 
Example #30
Source File: RuntimeTypeAdapterFactoryTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testDeserializeMissingSubtype() {
  TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
      .registerSubtype(BankTransfer.class);
  Gson gson = new GsonBuilder()
      .registerTypeAdapterFactory(billingAdapter)
      .create();
  try {
    gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class);
    fail();
  } catch (JsonParseException expected) {
  }
}